用里面的脚本设置innerHTML [英] setting innerHTML with a script inside
问题描述
如果我在任何页面上的Firebug中运行以下行:
If I run the following line in Firebug on any page:
document.documentElement.innerHTML="<script>alert(1)</script>";
为什么不执行 alert
命令?
推荐答案
看起来你的< script>
标签 is 按预期添加,但其中的代码未被执行。如果您尝试使用 document.head
(或任何其他DOM元素,似乎)会发生同样的故障。无论出于何种原因(可能符合标准,可能的安全性),通过 .innerHTML $ c添加的
< script>
块内的内联代码$ c>根本不运行。
It looks like that your <script>
tag is being added as you expect, but the code within it is not being executed. The same failure happens if you try using document.head
(or any other DOM element, it seems). For whatever reason (possibly standards compliance, possible security), inline code inside of <script>
blocks that are added via .innerHTML
simply doesn't run.
但是,我确实有工作代码可以产生类似的功能:
However, I do have working code that produces similar functionality:
var script = document.createElement('script');
script[(script.innerText===undefined?"textContent":"innerText")] = 'alert(1);';
document.documentElement.appendChild(script);
在这里,您添加< script>
阻止 documentElement.appendChild
并使用 textContent
或 innerText
设置< script>
的内容。
Here, you add the <script>
block with documentElement.appendChild
and use textContent
or innerText
to set the content of the <script>
.
这篇关于用里面的脚本设置innerHTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!