使用场景
当前项目中需要嵌套一个其他项目中的页面
实现过程
父页面
//创建一个iframe标签 并绑定id或者ref进行获取dom src为对应通信项目的路径地址 load事件为iframe加载完毕的回调
<div class="page-container">
<iframe id="iframeID" :src="updateLogUrl" frameborder="0" width="100%" height="100%"
@load="loadIframe" />
</div>
async mounted() {
this.updateLogUrl = `https://www.巴拉巴拉.com`;
},
loadIframe() {
//防止在子页面接收之前发送
setTimeout(() => {
let iframeWin = document.getElementById("iframeID").contentWindow;
let params = {};需要通信的参数
iframeWin.postMessage(JSON.stringify(params), "*");消息发送
}, 100);
},
子页面
// 我是直接放到了app.vue内mountd事件接收消息
window.addEventListener('message', function(event) {
// 检查消息来源,确保安全
if (event.origin !== 'http://allow-origin.com') return;
console.log('Received message:', event.data);
});