postMessage基本用法
otherWindow.postmessage(message, targetOrigin)
- otherWindow 其他窗口的一个引用,比如iframe的contentWindow属性, 执行window.open返回的窗口对象, 或者命名过数值索引的window.frames
- message 将要发送到其他window的数据. 它将会被结构化克隆算法序列化, 这意味着你可以不受什么限制的将数据对象安全的传送给目标窗口而无需自己序列化
- targetOrigin 通过窗口的orgin属性来指定那些窗口能接收到消息事件, 其值可以是字符串*(表示无限制)或者一个URI(目标窗口的协议,主机地址或端口这三者任意一项不匹配targetOrigin提供的值,那么消息就不会被发送)
实例
A给B发消息, B接收到消息后再给A发消息
// pageA
const pageB = window.open('http://127.0.0.1:5500/index1.html')
var btn = document.getElementById('sendMessage')
btn.addEventListener('click', function (e) {
e.preventDefault()
receiver.postMessage('info... from pageA', 'http://127.0.0.1:5500/')
})
// 监听message事件, 接收B页面发送过来的消息
window.addEventListener('message', function(e) {
if (e.origin !== 'http://127.0.0.1:5500') { // 验证消息来源
return
}
console.log(`从${e.origin}收到消息: ` + e.data)
})
// pageB
window.onload = function () {
// 监听message事件, 接收A页面发送过来的消息
window.addEventListener('message', function(e) {
if (e.origin !== 'http://127.0.0.1:5500') { // 验证消息来源地址
return
}
console.log(`从${e.origin}收到消息: ` + e.data)
// B页面发送消息给A
e.source.postMessage('info... from pageB' )
})
}