Reputation:
Can I use insertAdjacentHTML to execute inline javascript?
What works in the browser console:
$('body').append('<script>alert(1)</script>')
What I need to work in browser console:
document.body.insertAdjacentHTML('beforeend', '<script>alert(1)</script>');
The VanillaJS solution does not work. I would be glad about a reason
Upvotes: 2
Views: 895
Reputation: 4413
var script = document.createElement('script'); // create a new script element
script.innerText = "alert('Hello!');"; // InnerText property html-encodes the content,
document.body.append(script); //append innterText to script
Upvotes: 0
Reputation: 24136
Using insertAdjacentHTML
, although the script tag is added to the page, it won't be parsed or executed.
For the script to actually run you need to use createElement
:
var script = document.createElement('script');
script.innerText = "console.log('Hello!');";
document.body.append(script);
Upvotes: 1