【发布时间】:2016-02-24 01:37:03
【问题描述】:
我需要像在页面上的 iframe 中运行代码一样运行代码,这意味着当我在该代码中使用 window 时,它应该使用 iframe 的窗口对象。它不是我创建的 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 在其代码中使用 window 对象来正确创建工具提示。
所以我需要运行
Opentip(myelement, data);
好像我在 iframe 中运行它,但没有在 iframe 中定义它。
所以Opentip函数需要使用iframe窗口,而不是父窗口。
【问题讨论】:
-
最简单的方法是将 Opentip 脚本注入到 iframe 的文档中,方法是在其 dom 中添加一个外部脚本标签。然后你可以调用
frames["FrameName"].Opentip(frames["FrameName"].document.body, data)注入脚本:frames["FrameName"].document.body.appendChild(frames["FrameName"].document.createElement("script")).src="http://example.com/script.js"; -
框架的内容是否与您的网站来自同一来源(域名)?
-
我在 chrome 扩展 @MattiVirkkunen 的 content_script 中运行所有 javascript
-
@dandavis 我会试试你提到的
-
@MattiVirkkunen 是的(我错了,我误解了你所说的)
标签: javascript jquery html css iframe