postMessage
postMessage是什么?
window.postMessage() 方法可以安全地实现跨源通信。 我们通常用于iframe通信,只要两个页面具有相同的协议,端口号,他们就可以相互通信。同样,postMessage也提供了一种受控机制来规避此限制,只要正确使用,这种方法就很安全。
基本语法:父发送消息。
//主页面基本使用
otherWindow.postMessage(message, targetOrigin, [transfer]);
//otherWindow 其他窗口的一个引用比如iframe的contentWindow属性、执行window.open返回的窗口对象、或者是命名过或数值索引的window.frames,这个就很难理解,官方文档没有具体案例,就看的很迷糊,看我下面的案例
<iframe id="ifm" src="http://localhost:8081"></iframe>
let otherWindow = document.getElementById("ifm").contentWindow
//这里是第一种引用iframe的contentWindox属性
//targetOrigin,就是你要传消息的那个页面
基本语法:子页面接受消息
window.addEventListener('message',function(e){
if(e.origin == 'http://localhost:8080'){
console.log('接受到了父页面的消息')
console.log(e.origin,'父页面地址')
event.source.postMessage('子页面传给父页面的数据',e.origin)
}
})
小结:通过window.addEventListener('message',(e)=>{
console.log('收到通知的操作')
})
我们来看一个使用的实例:父页面。
<template>
<div>
<div>iframe的父页面</div>
<button id="send">点击发送信息</button>
<iframe id="ifm" src="http://localhost:8081"></iframe>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
},
mounted(){
//给子页面发送消息
let xmIframe = document.getElementById("ifm").contentWindow
let btn = document.getElementById('send');
btn.addEventListener('click', () => {
// iframe加载后, 向iframe发送参数
xmIframe.postMessage('true',"http://localhost:8081")
})
//接受子页面消息
window.addEventListener('message',function(e){
console.log(e.data)
})
}
}
</script>
<style scoped>
</style>
</style>
子页面
<template>
<div class="hello">
<div>我是子页面</div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
mounted() {
window.addEventListener('message',function(e){
if(e.origin == 'http://localhost:8080'){
console.log('接受到了父页面的消息')
console.log(e.origin,'父页面地址')
event.source.postMessage('子页面传给父页面的数据',e.origin)
}
})
},
}
</script>
<style scoped>
</style>
小结:这里要注意几个地方,首先要判断发送消息的页面,是否是你想要的的,e.origin,可以取到发送消息的那个页面的url,event.source可以对发送消息窗口对象的引用,等于你父页面取子页面窗口引用的那个步骤。
总结:其实很简单的一个东西,但是官方文档语术太专业,某度文档又太杂乱,导致看了很久都没明白,写了demo结合官方文档才完全吸收。