如何将数据从 iram 传递到父级

Emz*_*ltd 1 javascript iframe

我正在创建一个托管在我的子域中的 vue js 应用程序

我想使用 iframe.simple 从我的主站点加载一个表单 我想通过 iframe 从我的主域加载一个表单到我的子域。并且工作正常

<iframe ref="formFrame" @load="afterLoad()" :src="url"></iframe> 
Run Code Online (Sandbox Code Playgroud)

现在我的 vue js 应用程序中有一个函数,例如

displaySuccess(data){
            console.log("data from server: "+data);
        }
Run Code Online (Sandbox Code Playgroud)

这个函数应该从我的表单触发。所以我在表单中添加了如下代码

window.parent.displaySuccess(text);
Run Code Online (Sandbox Code Playgroud)

但它没有触发。我如何从 iframe 表单调用父方法。提前致谢

Ran*_*ner 6

您可以window.postMessage()安全地使用该方法(启用 Window 对象之间的跨源通信;例如,页面与其生成的弹出窗口之间,或者页面与嵌入其中的 iframe 之间,如您的示例中所示)。

这是父级与 Iframe 之间双工通信的基本示例。

父级 -> IFrame

   iframe.contentWindow.postMessage('hello world', '*'); // from parent
Run Code Online (Sandbox Code Playgroud)
window.onmessage = function(e) { // inside the iframe
    if (e.data == 'hello world') {
        alert('It works!');
    }
};
Run Code Online (Sandbox Code Playgroud)

IFrame -> 父级

window.onmessage = function(e) { // inside the parent
    if (e.data == 'hello world') {
        alert('It works!');
    }
};
Run Code Online (Sandbox Code Playgroud)
window.top.postMessage('hello world', '*') //inside the iframe
Run Code Online (Sandbox Code Playgroud)

Window.postMessage - https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage