接收传递的消息时,可以将
window.addEventListener('message', function(e) {
console.log(e.data)
})写法,更换为
window.onmessage = async function(e) {}
可以避免消息发送后,多次接收该参数
父页面js
IframeEvent(){
const send = document.getElementById('myIframe')
if (send) {
//(只能传递文字,传递对象使用JSON转成字符串再传递)
send.contentWindow.postMessage("传递的数据", '*')
}
},
子页面(iframe)
//创建监听,进行数据接收
window.addEventListener('message',function(e){
console.log(e.data)
})
//给父页面传值
window.parent.postMessage('I am xiaojin', '*')
//父页面接收值也是使用window创建message监听进行值的接收
window.addEventListener('message', function(e) {
console.log(e.data)
})