如何将数据从 iframe 传递给父级
How to pass data from ifram to parent
我正在创建一个托管在我的子域中的 vue js 应用程序
我想使用 iframe.simple 从我的主站点加载一个表单 我想通过我从我的主域加载一个表单到我的子域 frame.And 工作正常
<iframe ref="formFrame" @load="afterLoad()" :src="url"></iframe>
现在我的 vue js 应用程序中有一个功能,例如
displaySuccess(data){
console.log("data from server: "+data);
}
而且这个函数应该从我的表单中触发。所以我在表单
中添加了如下代码
window.parent.displaySuccess(text);
但不是triggering.How我可以提前从 iframe form.Thanks 调用父方法吗
您可以安全地使用 window.postMessage()
方法(启用 Window 对象之间的跨源通信;例如,在页面和它生成的弹出窗口之间,或在页面和iframe 嵌入其中,就像您的示例一样)。
这是父级和 Iframe 之间双工通信的基本示例。
父级 -> IFrame
iframe.contentWindow.postMessage('hello world', '*'); // from parent
window.onmessage = function(e) { // inside the iframe
if (e.data == 'hello world') {
alert('It works!');
}
};
IFrame -> 父级
window.onmessage = function(e) { // inside the parent
if (e.data == 'hello world') {
alert('It works!');
}
};
window.top.postMessage('hello world', '*') //inside the iframe
Window.postMessage - https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
我正在创建一个托管在我的子域中的 vue js 应用程序
我想使用 iframe.simple 从我的主站点加载一个表单 我想通过我从我的主域加载一个表单到我的子域 frame.And 工作正常
<iframe ref="formFrame" @load="afterLoad()" :src="url"></iframe>
现在我的 vue js 应用程序中有一个功能,例如
displaySuccess(data){
console.log("data from server: "+data);
}
而且这个函数应该从我的表单中触发。所以我在表单
中添加了如下代码window.parent.displaySuccess(text);
但不是triggering.How我可以提前从 iframe form.Thanks 调用父方法吗
您可以安全地使用 window.postMessage()
方法(启用 Window 对象之间的跨源通信;例如,在页面和它生成的弹出窗口之间,或在页面和iframe 嵌入其中,就像您的示例一样)。
这是父级和 Iframe 之间双工通信的基本示例。
父级 -> IFrame
iframe.contentWindow.postMessage('hello world', '*'); // from parent
window.onmessage = function(e) { // inside the iframe
if (e.data == 'hello world') {
alert('It works!');
}
};
IFrame -> 父级
window.onmessage = function(e) { // inside the parent
if (e.data == 'hello world') {
alert('It works!');
}
};
window.top.postMessage('hello world', '*') //inside the iframe
Window.postMessage - https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage