将一个JavaScript函数注入到iframe中 [英] inject a javascript function into an Iframe

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

问题描述

链接描述如何从代码注入代码脚本成为iframe:

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

我想将foo的代码插入iframe吗? ( function 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 =< script> + foo.toString()+< / script>

获取函数内的代码,但


  • 我不知道如何将它插入到iframe HEAD中(也许用jquery?)

  • 我不知道这是否正确的方式

  • 我不知道如果功能比这个方式更复杂,那么会发生什么

  • 我不知道发生在 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

任何提示? >

Any hint?

推荐答案

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

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直接操纵框架的DOM和窗口对象:

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中的范围没有改变,所以窗口仍然是父窗口等内部foo。

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

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

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中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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