user8417018
user8417018

Reputation:

Can't execute inline script with Element.insertAdjacentHTML()

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

Answers (2)

Parth Raval
Parth Raval

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

Peter B
Peter B

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

Related Questions