3

How to do that:

document.getElementById('target').innertHTML = "<script> alert(1); <script>";
<div id="target"></div>

script will be print on browser like a string.How to do is as script ?

4 Answers 4

9

I believe it is better to use pure DOM manipulation. Like this :

var s = document.createElement('script');
s.setAttribute('type', 'text/javascript');
s.value = 'alert(1)';
document.getElementById('target').appendChild(s);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for replying my question. I am voting for you.
5

Just don't escape your < and >s:

document.getElementById('target').innertHTML = "<script> alert(1); <\/script>";

2 Comments

You might want to use <\/script> so the script tag that that code is in doesn't get closed in the middle of a string literal.
don't write it in script tags, i have used creatElement . Thanks :D
0

You cannot use innerHTML for scripts anymore. It won't work and the console will not show any error. Instead you dynamically add scripts.

This is for external scripts:

var newScript = document.createElement("script");
newScript.src = "http://www.example.com/my-script.js";
target.appendChild(newScript);

And this is for inline scripts:

var newScript = document.createElement("script");
var inlineScript = document.createTextNode("alert('Hello World!');");
newScript.appendChild(inlineScript); 
target.appendChild(newScript);

Credit to Daniel Crabtree

Comments

-1
document.getElementById('target').innertHTML = '<script type="text/javascript"> alert(1); </script>';

1 Comment

This doesn't execute/ evaluate the injected script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.