将 javascript 函数注入 Iframe [英] inject a javascript function into an Iframe
本文介绍了将 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 = "