Can malicious javascript code be injected through $()? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Can malicious javascript code be injected through $()? without wasting too much if your time.

The question is published on by Tutorial Guruji team.


if($('#' + untrusted_js_code).length) > 0

Normally “untrusted_js_code” should be a simple string representing the ID of an item. The value of the variable comes from an iframe (trough postMessage), this is why it’s untrusted. And I’m just checking if that item exists in the current page, and only then do stuff with it.


As of 22/10/2012, jQuery 1.8.2:

Yes, XSS attacks are possible.

var input = "<script>alert('hello');</script>"

See demo. It seems the jQuery team has acknowledged this and has plans to address it in jQuery 1.9.

As of jQuery 1.8, use $.parseHTML if you expect user input to be html:

var input = "<script>alert('hello');</script>"

See demo, no alerts.

In the case OP describes however, the following:

var untrusted_js_code = 'alert("moo")';
$('#' + untrusted_js_code).show();

Will translate to this:


This is intrepreted by jQuery as a CSS selector, thanks to the preceding # in the string, which as oppposed to html cannot have in-line JS code, so it is relatively safe. The code above would only tell jQuery to look for a DOM element by that ID, resulting in jQuery failing to find the element and thus not performing any action.

We are here to answer your question about Can malicious javascript code be injected through $()? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji