window.postMessage()方法可以实现Window对象之间的跨源通信,例如:页面和它的弹窗,页面和嵌入其中的iframe之间。
父页面
// iframe
<iframe ref="iframe" id="iframe" src="http://localhost:9527/general/product/home/homePage" frameborder="0" class="iframe-section"></iframe>
// 接收iframe中传过来的数据
window.addEventListener('message', event => {
// 判断信息是不是特定的iframe中发送过来的,如果子页面未指定目标源,也可以不判断
if(event.origin === 'http://localhost:9527') {
this.$message.success(event.data)
}
}, false)
// 向iframe中传递数据
document.querySelesctor('#iframe').contentWindow.postMessage('haha', 'http://localhost:9527')
// * 表示可以向任何页面传递信息(存在安全问题,可能会被其他网站截取数据)
// document.querySelesctor('#iframe').contentWindow.postMessage('haha', '*')
iframe / 子页面 / 弹窗
// 接收父页面中传过来的数据
window.addEventListener('message', event => {
if(event.origin === 'http://localhost:8080') {
this.$message.success(event.data)
}
}, false)
// 向父页面传递数据
window.parent.postMessage('heihei', 'http://localhost:8080')
// window.parent.postMessage('heihei', '*')