iframe通讯必备(postMessage)

postMessage

postMessage是什么?

window.postMessage() 方法能够安全地实现跨源通讯。 咱们一般用于iframe通讯,只要两个页面具备相同的协议,端口号,他们就能够相互通讯。一样,postMessage也提供了一种受控机制来规避此限制,只要正确使用,这种方法就很安全。安全

基本语法:父发送消息。markdown

//主页面基本使用
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,就是你要传消息的那个页面

复制代码

基本语法:子页面接受消息oop

  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)=>{post

console.log('收到通知的操做')ui

})url

咱们来看一个使用的实例:父页面。spa

xml

<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")code

})
//接受子页面消息
 window.addEventListener('message',function(e){
         console.log(e.data)
    })
复制代码

} } </script> <style scoped>orm

复制代码}) //接受子页面消息 window.addEventListener('message',function(e){ console.log(e.data) }) 复制代码</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结合官方文档才彻底吸取。

相关文章
相关标签/搜索