简体   繁体   English

您可以运行写入DOM(内部HTML)的JavaScript吗?

[英]Can you run javascript that is written into the DOM (inner HTML)?

For instance: 例如:

document.getElementById("test").innerHTML= "<script>document.write('worked')</script>";

The result is: 结果是:

<div id="test"><script>document.write('worked')</script></div>

ie no JS is run. 即没有运行JS。 Why don't I just make .innerhtml "worked" to start with? 为什么我不只是让.innerhtml开始工作呢? This is a question of technical ability. 这是技术能力的问题。 Is it possible to run javascript in the DOM with the given scenario? 是否可以在给定情况下在DOM中运行javascript?

Thank you 谢谢

It's not enough to simply set the innerHTML to something that contains a script tag. 仅将innerHTML设置为包含脚本标签的内容是不够的。 You must create a script element and append it to the DOM. 您必须创建一个脚本元素并将其附加到DOM。 I believe the intent is to give some cross site scripting protection when injecting massive blobs of content. 我相信目的是在注入大量内容时提供一些跨站点脚本保护。

var script = document.createElement('script');
script.innerHTML = "alert('ran some JS');";
document.body.appendChild(script);

Example: http://jsfiddle.net/axvaT/ 示例: http//jsfiddle.net/axvaT/

document.write won't work like you think though. document.write无法像您想的那样工作。 document.write will not place text where the script tag is. document.write不会在script标签所在的位置放置文本。 Instead it will place text where the HTML parser is currently looking at. 而是将文本放置在HTML解析器当前正在查看的位置。 Depending on when the JS code is run, these may be the same, or maybe entirely different. 根据运行JS代码的时间,它们可能相同,也可能完全不同。

So for this reason, among others, never use document.write for anything. 因此,出于这个原因,决不要将document.write用于任何东西。 Ever. 曾经 Even debugging. 甚至调试。


Lastly, while sometimes it's useful to inject a script tag pointing to some other js file: 最后,虽然有时插入指向其他js文件的脚本标签很有用:

var script = document.createElement('script');
script.src = 'somefile.js';
document.head.appendChild(script);

Doing this with a script tag that has JS in it makes no sense. 使用包含JS的脚本标签执行此操作没有任何意义。 You are using javascript to create a script tag that should immediately run some javascript. 您正在使用javascript创建应立即运行某些javascript的脚本标记。 Why not just run that javascript that you want to run away instead of creating a new script tag to do it for you? 为什么不运行您想逃跑的JavaScript而不是创建一个新的脚本标签来帮您呢?

So don't do: 所以不要:

var script = document.createElement('script');
script.innerHTML = "alert('ran some JS');";
document.body.appendChild(script);

Instead just do: 而是做:

alert('ran some JS');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM