40

This link (archived version) describes how to inject code from a script into an iframe:

function injectJS() {
  var iFrameHead = window.frames["myiframe"].document.getElementsByTagName("head")[0];
  var myscript = document.createElement('script');
  myscript.type = 'text/javascript';
  myscript.src = 'myscript.js'; // replace this with your SCRIPT
  iFrameHead.appendChild(myscript);
}

That's ok, but what if I want to insert a function object into an iframe and get it executed in the iframe context? Let's say I have:

function foo () {
    console.log ("Look at me, executed inside an iframe!", window);
}

and I want to insert foo's code inside an iframe? (function foo could be something loaded dynamically, I can't just wrap it in quotes)

I naively tried:

var scriptFooString = "<script>" + foo.toString() + "</script>"

to get the code inside function, but

  • I don't know how to insert it in the iframe HEAD (maybe with jquery?)
  • I don't know if it's the right way
  • I don't know what happens when if function is way more complex than that
  • I don't know what happens with double and single quotes in scriptFooString

Any hint?

4

3 回答 3

40

首先,如果您的框架和显示它的页面在同一个域中,您只能完成此操作(由于跨域规则)

其次可以通过JS直接操作frame的dom和window对象:

frames[0].window.foo = function(){
   console.log ("Look at me, executed inside an iframe!", window);
}

要从 DOMElement 对象中获取框架,您可以使用:

var myFrame = document.getElementById('myFrame');

myFrame.contentWindow.foo = function(){
       console.log ("Look at me, executed inside an iframe!");
}

请注意,foo 中的范围没有改变,因此 window 仍然是 foo 中的父窗口等。

如果你想注入一些需要在另一个框架的上下文中运行的代码,你可以注入一个脚本标签,或者评估它:

frames[0].window.eval('function foo(){ console.log("Im in a frame",window); }');

虽然普遍的共识是永远不要使用 eval,但如果你真的需要这样做,我认为它比 DOM 注入更好。

因此,在您的特定情况下,您可以执行以下操作:

frames[0].window.eval(foo.toString());
于 2013-04-24T14:29:37.863 回答
4

这段代码是我研究的结果。接受的答案也对我有很大帮助。首先,我创建了一个简单的 iframe:

<iframe id="myiframe" width="200" height="200" srcdoc="<h1 id='title'>Hello from Iframe</h1><button type='button' id='fire'>Click Me!</button>
"></iframe>

为了访问 iframe 的窗口和文档,我使用了这段代码。

const iframe = document.getElementById('myiframe');
const iframeWin = iframe.contentWindow || iframe;
const iframeDoc = iframe.contentDocument || iframeWin.document;

最后我将js代码注入iframe:

var script = iframeDoc.createElement("script");
  script.append(`
    window.onload = function() {
     document.getElementById("fire").addEventListener('click', function() {
        const text = document.getElementById('title').innerText;
        alert(text);
     })
  }
`);
  iframeDoc.documentElement.appendChild(script);

演示: https ://jsfiddle.net/aliam/1z8f7awk/2/

于 2020-12-23T12:51:56.420 回答
2

这是我的解决方案。我正在使用 jquery 插入内容,然后使用 eval 在该 iframe 的上下文中执行脚本标签:

    var content = $($.parseHTML(source, document, true));
    $("#content").contents().find("html").html(content);
    var cw = document.getElementById("content").contentWindow;
    [].forEach.call(cw.document.querySelectorAll("script"), function (el, idx) {
        cw.eval(el.textContent);
    });
于 2016-10-14T03:52:55.163 回答