Javascript 如何在iFrame中未定义的iFrame中运行代码?
我需要像在页面上的iframe中一样运行代码,这意味着当我在该代码中使用Javascript 如何在iFrame中未定义的iFrame中运行代码?,javascript,jquery,html,css,iframe,Javascript,Jquery,Html,Css,Iframe,我需要像在页面上的iframe中一样运行代码,这意味着当我在该代码中使用window时,它应该使用iframe的window对象。它不是我创建的iframe,因此没有在其中定义我的函数 var myfunction = function () { // defined in parent, not in the iframe console.log(window); // window here should be the iframe's window object, not the pa
window
时,它应该使用iframe的window对象。它不是我创建的iframe,因此没有在其中定义我的函数
var myfunction = function () { // defined in parent, not in the iframe
console.log(window); // window here should be the iframe's window object, not the parent/
window.document.body.appendChild("Appending to iframe body");
}
// Need to somehow run this function inside the iframe
myfunction(); // as if I did this inside the iframe
我需要在iframe中运行这个精确的代码,我知道我可以自己修复它
frames["FrameName"].document.body.appendChild("Appending to iframe body");
但这并不能解决我的问题
这是因为我没有自己编写代码,有一个名为Opentip的模块,我用来创建工具提示。我需要在iframe内的元素上设置工具提示;但是,Opentip使用其代码中的窗口
对象来正确创建工具提示
所以我需要跑步
Opentip(myelement, data);
就像我在iframe中运行它一样,但没有在iframe中定义它
因此Opentip函数需要使用iframe窗口,而不是父窗口。提供的代码当然未经测试。这是假设的答案:
- OP情况是符合
相同原产地政策的要求
- OP无法直接编辑子页面
- OP不能使用Ajax
//A//iframe的引用
var iFrm=document.getElementById('iFrm')
//B//侦听加载事件
iFrm.addEventListener('load',函数(e){
//C//Ref到iframe窗口
var iWin=iFrm.contentWindow;
//D//iframe文档的参考
var iDoc=iFrm.contentDocument?iFrm.contentDocument:iFrm.contentWindow.document;
//E//Ref Opentip指向的元素--replace{{>selsel最简单的方法是通过向iframe的dom添加外部脚本标记将Opentip脚本注入iframe的文档中。然后可以调用frames[“FrameName”].Opentip(frames[“FrameName”].document.body,data)
注入脚本:frames[“FrameName”].document.body.appendChild(frames[“FrameName”].document.createElement(“脚本”)).src=”http://example.com/script.js“;
框架的内容是否来自同一来源(域名)作为您的站点?我正在chrome扩展中的content_脚本中运行所有javascript@MattiVirkkunen@dandavis我会试试你想要的mentioned@MattiVirkkunen是的,的确如此(我的错,我误解了你说的话),我遇到了一些奇怪的事情。有一次我调用iFrm.contentWindow.Opentip
(在加载事件侦听器中)它说,iFrm.contentWindow.Opentip
仍然未定义,但在它给出该错误后,我在浏览器控制台中再次手动检查,它存在(我可以运行它)…我不确定,但我认为事件侦听器可能正在对存储在iFrm.contentWindo.Opentip
中未定义的数据进行快照,而不是访问新定义的函数。有什么想法吗?如果得到奇怪的结果,很可能是因为Opentip绑定到窗口。当调用函数时,正确的上下文必须建立xt。不幸的是,它并不是简单地将窗口视为全局窗口,因为您是从子页面调用的,实际窗口可能被视为父窗口,而不是属于子页面的窗口。要获得对子窗口的正确引用,我认为需要从父窗口发起调用。请尝试ifrm.contentWindow.document.Opentip
或parent.contentDocument.document.Opentip