我正在尝试在网页中运行脚本,该脚本应在 <iframe>
中执行.现在我可以调用 <iframe>
中设置的函数.. 我只是在向 <iframe>
运行脚本时遇到问题的上下文。
以下是我如何运行 <iframe>
中的函数集
$('#iframe').get(0).contentWindow.performSearch();
现在不再调用 preformSearch
函数,我希望运行一个脚本 - 对于这个例子,这是脚本...
console.log('worked!');
我的实际脚本很大,所以为了这个问题我不会把它放在这里。
那么,有什么方法可以通过 <iframe>
运行该脚本吗?的上下文?例如,我的第一个猜测是/是..
$('#iframe').get(0).contentWindow.function(){
console.log('worked!');
}
我从来没有通过类似 <iframe>
的方式搞乱运行函数虽然之前,所以我很难过。
提前感谢您的帮助!
注意 我正在使用 NW.js (Node-Webkit) 删除所有 <iframe>
限制。
注意 v2 preformSearch()
函数只是对我如何在框架中调用函数的引用。
最佳答案
您可以尝试使用消息传递机制 这意味着您可以在父框架上发送消息
var win =$("#iframe").contentWindow;
win.postMessage({ messageType: "predefinedMessage", features: data }, '*');
而且在 iframe 中你可以获得消息
function FrameCommunicator(attachManager) {
var mfilesFrame;
function _actOnMessage(data) {
if (data.messageType === "predefinedMessage") {
//perform here what you need
}
}
window.addEventListener("message", function (e) {
var data = e.data;
mfilesFrame = e.source;
_actOnMessage(data);
}, false);
}
现在的问题是,如果 iframe 和父 fram 引用远程,则它们可以具有相同的代码。
另一种方法是将消息的内容作为 JS 发送并使用 eval 运行它,但这是有风险的,不好的做法和很多其他事情:)
关于javascript - 在 iFrame 上下文中运行 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30063806/