本文介绍了将 javascript 函数注入 Iframe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此链接 (存档版本) 描述如何将脚本中的代码注入 iframe:

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);
}

没关系,但是如果我想将一个函数对象插入到 iframe 并让它在 iframe 上下文中执行怎么办?假设我有:

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);
}

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

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)

我天真地尝试过:

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

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

to get the code inside function, but

  • 我不知道如何将它插入 iframe HEAD(也许使用 jquery?)
  • 我不知道这是否正确
  • 我不知道当 if 函数比那复杂得多时会发生什么
  • 我不知道 scriptFooString 中的双引号和单引号会发生什么
  • 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

有什么提示吗?

推荐答案

首先,只有当你的框架和显示它的页面在同一个域内时,你才能做到这一点(由于跨域规则)

First of all you can only accomplish this if your frame and the page displaying it is within the same domain (Due to cross-domain rules)

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

secondly you can manipulate dom and window objects of the frame directly through JS:

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

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

to get your frame from a DOMElement object you can use:

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

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

注意 foo 中的作用域没有改变,所以 window 仍然是 foo 中的父窗口等.

Note that the scope in foo is NOT changed, so window is still the parent window etc. inside foo.

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

If you want to inject some code that needs to be run in the context of the other frame you could inject a script tag, or eval it:

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

虽然普遍的共识是永远不要使用 eval,但我认为如果您真的需要完成它,我认为它比 DOM 注入更好.

Though the general consensus is to never use eval, I think its a better alternative than DOM injection if you REALLY need to accomplish this.

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

So in your specific case you could do something like:

frames[0].window.eval(foo.toString());

这篇关于将 javascript 函数注入 Iframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 04:38
查看更多