Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script Execution - innerHTML, jQuery html()

document.body.innerHTML = "<script>alert(11);</script>"

$("body").html("<script>alert(11);</script>")

innerHTML is not executed.

jQuery html() is executed.

Why so?

like image 553
user3336280 Avatar asked Sep 16 '26 13:09

user3336280


1 Answers

Without getting into the theoretical questions of why jQuery chose to do this, the jQuery html() behaves differently than the native innerHTML. By default, jQuery will find the script tags within the HTML, and load then asynchronously. If this behavior is undesirable, you can use $.parseHTML to prevent this from happening by setting the third argument to false.

$("body").empty().append($.parseHTML("<script>alert(11);</script>", document, false));

Note that the script tags will not be added to the DOM using this method.

Conversely, if you wish to achieve the same affect as your jQuery statement in vanilla JS, you can do the following.

var script = document.createElement('script');
script.text = 'alert(11);';
document.body.innerHTML = '';
document.body.appendChild(script);
like image 120
Alexander O'Mara Avatar answered Sep 18 '26 02:09

Alexander O'Mara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!