最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Is there anyway of getting javascript code injected in an iframe to execute without removing and reappending the script tag cont

programmeradmin1浏览0评论

Context:

I am building a live HTML,CSS & Javascript editor. 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? 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.

Thanks!

Context:

I am building a live HTML,CSS & Javascript editor. 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? 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.

Thanks!

Share Improve this question asked Oct 7, 2012 at 22:19 zeusdeuxzeusdeux 5211 gold badge6 silver badges14 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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

pare 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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论