html() vs innerHTML jquery/javascript & XSS attacks

This is similar to both this question and this one. .html() strips out the script tags before it inputs the HTML and executes them separately.

As for why the second one is not being executed, it is because dynamically added scripts like that will not be run after the page has been loaded.

But, as @Ben points out, there are a lot of XSS openings when accepting things like that. That said, if the information is being displayed on their own page, they can run any arbitrary code they want on their own machine. The big issue will be if you store this, or send this to other users. Unless you do that, there is no protecting users from themselves in these sorts of regards. Maybe knowing what you're trying to protect against will help.


JQuery strips out the script tags, which is why you aren't seeing it append to the dom let alone executing.

To see an explanation of why jquery strips it out, you can see John Resig's reply here: https://forum.jquery.com/topic/jquery-dommanip-script-tag-will-be-removed

Hope this helps


yes jquery html won't render script tags

but it isn't more secure because you can use many other xss payloads such as <a href> style , expression etc..


Contrary to what is being said in the accepted answer, jQuery.html() and the many jQuery functions which accept HTML strings as arguments are more prone to DOM-based XSS injection than innerHTML, as noticed by the OP.

jQuery.html() extracts the <script> tags, updates the DOM and evaluates the code embedded in the script tags.

As a result, XSS can happen without user interaction even after the DOM is loaded when using jQuery.html().

This is very easy to demonstrate.

This will call alert():

$('.xss').html('<script>alert("XSS");</script\>');

http://jsfiddle.net/2TpHC/

While this will not:

var d = document.getElementById('xss');
d.innerHTML = '<script\>alert("XSS");</script\>';

http://jsfiddle.net/Tjspu/

Unfortunately, there are many other code paths (sinks) which lead to calling eval() in jQuery. The security conscious will probably avoid jQuery altogether, as far as possible.

Note that I do not claim that using innerHTML is an effective defense against XSS. It is not. Passing unescaped data to innerHTML is not safe, as pointed out by @daghan. One should always properly escape data when generating HTML.