将JavaScript函数注入iframe

jan*_*nce 32 javascript iframe dom head

此链接(存档版本)描述了如何将脚本中的代码注入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);
}
Run Code Online (Sandbox Code Playgroud)

没关系,但如果我想将一个函数对象插入iframe 并在iframe上下文中执行它会怎样?比方说我有:

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

我想在iframe中插入foo的代码?(函数foo可能是动态加载的东西,我不能只用引号括起来)

我天真地尝试过:

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

获取函数内部的代码,但是

  • 我不知道如何将它插入iframe HEAD(也许用jquery?)
  • 我不知道这是不是正确的方法
  • 我不知道当函数比这更复杂时会发生什么
  • 我不知道双引号和单引号会发生什么 scriptFooString

任何提示?

EJT*_*JTH 35

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

其次,您可以通过JS直接操作框架的dom和window对象:

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

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

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

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

请注意,foo中的范围未更改,因此窗口仍然是foo中的父窗口等.

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

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

虽然普遍的共识是永远不会使用eval,但我认为如果你真的需要实现这个,它是一个比DOM注入更好的选择.

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

frames[0].window.eval(foo.toString());
Run Code Online (Sandbox Code Playgroud)

  • 我需要在沙箱中执行动态加载的插件(带有requirejs).你知道更好的方法吗? (3认同)

Ali*_*ari 8

This code is the result of my research. The accepted answer also helped me a lot. First of all, I create a simple 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>
Run Code Online (Sandbox Code Playgroud)

For access to iframe's window and document I used this code.

const iframe = document.getElementById('myiframe');
const iframeWin = iframe.contentWindow || iframe;
const iframeDoc = iframe.contentDocument || iframeWin.document;
Run Code Online (Sandbox Code Playgroud)

Finally I injected js codes into 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);
Run Code Online (Sandbox Code Playgroud)

Demo: https://jsfiddle.net/aliam/1z8f7awk/2/