简体   繁体   English

有没有在iframe中注入javascript代码执行而不删除并重新发布包含它的脚本标记?

[英]Is there anyway of getting javascript code injected in an iframe to execute without removing and reappending the script tag containing it?

Context: 语境:

I am building a live HTML,CSS & Javascript editor. 我正在构建一个实时的HTML,CSS和Javascript编辑器。 It can be accessed here . 它可以在这里访问。

The source can be accessed here . 源可以在这里访问。

Question: 题:

Is it possible to run javascript code injected into an iframe without repeated removal and addition of <script> tag containing the code from and to the DOM tree? 是否可以运行注入iframe的javascript代码而无需重复删除并添加包含DOM树代码的<script>标记? Since DOM manipulation is a costly affair, I want to try and eliminate multiple DOM manipulations. 由于DOM操作是一项代价高昂的事情,我想尝试消除多个DOM操作。 Instead I want to be able to just change the textContent of the <script> tag and have it run the new code that I've inserted. 相反,我希望能够只更改<script>标记的textContent并让它运行我插入的新代码。

Thanks! 谢谢!

If you don't mind using the evil eval , you can re-evaluate most JavaScript in the iframe's window, for example 例如,如果你不介意使用邪恶的 eval ,你可以重新评估iframe窗口中的大多数JavaScript

function someFunction(){                                // any function
    console.log(document.body.children);
}

someFunction();                                         // see normal output

var ifrm  = document.getElementsByTagName('iframe')[0], // your iframe
    iwind = ifrm.contentWindow;                         // the iframe's window

iwind.eval( someFunction.toString() );                  // re-evaluate function with eval from iframe
iwind.someFunction();                                   // see new output - output is in iframe's context

compare against 比较

iwind.someFunction = someFunction;                      // set variable
iwind.someFunction();                                   // same as calling someFunction() from parent

It should work for most valid JavaScript (take into account scope), but be aware that using eval can be bad . 它应该适用于大多数有效的JavaScript(考虑范围),但要注意使用eval可能很糟糕

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

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