开发者

javascript - how to insert a script tag to div?

开发者 https://www.devze.com 2023-04-02 04:35 出处:网络
How to do that: document.getElementB开发者_如何学GoyId(\'target\').innertHTML = \"<script> alert(1); <script>\";

How to do that:

document.getElementB开发者_如何学GoyId('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 ?


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);


Just don't escape your < and >s:

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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消