有没有在iframe中注入javascript代码执行而不删除并重新发布包含它的脚本标记? [英] Is there anyway of getting javascript code injected in an iframe to execute without removing and reappending the script tag containing it?

查看:131
本文介绍了有没有在iframe中注入javascript代码执行而不删除并重新发布包含它的脚本标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上下文:

我正在构建一个实时HTML,CSS& Javascript编辑器。
可以访问此处

I am building a live HTML,CSS & Javascript editor. It can be accessed here.

可以通过此处访问来源。

问题:

是否可以运行注入iframe的javascript代码,而无需重复删除和添加< script>包含DOM树代码的标签?由于DOM操作是一项代价高昂的事情,我想尝试消除多个DOM操作。
相反,我希望能够只更改< script>的 textContent 。标记,让它运行我插入的新代码。

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? Since DOM manipulation is a costly affair, I want to try and eliminate multiple DOM manipulations. 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.

谢谢!

推荐答案

如果您不介意使用 evil eval ,您可以重新评估iframe窗口中的大多数JavaScript,例如

If you don't mind using the evil eval, you can re-evaluate most JavaScript in the iframe's window, for example

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

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

它适用于大多数有效的JavaScript(考虑到范围),但请注意使用 eval 可能不好

It should work for most valid JavaScript (take into account scope), but be aware that using eval can be bad.

这篇关于有没有在iframe中注入javascript代码执行而不删除并重新发布包含它的脚本标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆