一、父ifram向子页面发送消息
//父ifram
mounted() {
//获取iframe元素
let iFrame = document.getElementById("myframe");
//iframe加载完毕后再发送消息,否则子页面接收不到message
iFrame.onload = function() {
//iframe加载完立即发送一条消息
console.log("获取ifram", iFrame.contentWindow);
iFrame.contentWindow.postMessage("我是ifram加载后的消息", "*");
};
},
//子页面
mounted() {
//监听message事件
window.addEventListener("message", this.receiveMessageFromIndex, false);
},
methods: {
receiveMessageFromIndex(event) {
console.log("receiveMessageFromIndex", event.data);
},
}
二、子页面向父ifram发送消息
//子页面
parent.postMessage({ msg: "从子页面返回来的信息" }, "*");
//父ifram
mounted() {
//监听message事件
window.addEventListener("message", this.receiveMessageFromIndex, false);
},
methods: {
receiveMessageFromIndex(event) {
console.log("receiveMessageFromIndex", event.data);
},
},
网友评论