简体   繁体   English

从iframe内部调用父Javascript函数

[英]Call parent Javascript function from inside an iframe

I have a iframe (in my domain), that iframe has a file iframe.js . 我有一个iframe(在我的域中),iframe有一个文件iframe.js

My parent document has a file parent.js . 我的父文档有一个文件parent.js

I need to call a function that is in parent.js , from a function that is in iframe.js . 我需要调用一个函数,在parent.js ,从一个函数,在iframe.js

I tried doing window.parent.myfunction() this function is in the parent.js file. 我试过做window.parent.myfunction()这个函数在parent.js文件中。

But, it didn't work. 但是,它没有用。 Only when I put the function on the parent page (I mean in the HTML), then it worked. 只有当我把这个函数放在父页面上时(我的意思是在HTML中),它才有效。

Any idea how to get this to work? 知道如何让这个工作吗?

Try just parent.myfunction() . 试试parent.myfunction() Also be 100% sure that the parent.js is included in your parent document. 还要100%确定parent.js包含在父文档中。

I know this is an old question, but in case the accepted answer doesn't work (it didn't work for me) you could do this inside parent.js 我知道这是一个老问题,但如果接受的答案不起作用(它对我不起作用)你可以在parent.js中做到这一点

window.myfunction = function () {
   alert("I was called from a child iframe");
}

Now from the iframe you can call myfunction() like you initially wanted 现在从iframe你可以像你最初想要的那样调用myfunction()

window.parent.myfunction(); 

Window.postMessage() method safely enables cross-origin communication. Window.postMessage()方法安全地启用cross-origin通信。

If you have access to parent page then any data can be passed as well as any parent method can be called directly from Iframe . 如果您可以访问父页面,则可以传递任何数据,也可以直接从Iframe调用任何父方法。

Parent page: 父页面:

if (window.addEventListener) {
    window.addEventListener("message", onMessage, false);        
} else if (window.attachEvent) {
    window.attachEvent("onmessage", onMessage, false);
}

function onMessage(event) {
    // Check sender origin to be trusted
    if (event.origin !== "http://example.com") return;

    var data = event.data;      
    if (typeof(window[data.func]) == "function") {
        window[data.func].call(null, data.message);
    }
}

// Function to be called from iframe
function parentFuncName(message) {
    alert(message);
}

Iframe code: iframe代码:

window.parent.postMessage({
    'func': 'parentFuncName',
    'message': 'Message text from iframe.'
}, "*");

References: 参考文献:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM