浏览器跨tab通信

window.open + window.postMessage

我们使用window.open打开页面时,方法会返回一个被打开页面window的引用,可以通过window.postMessage的方式去通信

但如果页面不是通过在另一个页面内的window.open打开的(例如直接在地址栏输入,或从其他网站链接过来),这种方式就不能使用

父页面A-->子页面B

父页面A

<template>
  <div>
    <div>这是父页面A</div>
    <button @click="openPage">打开子页面B</button>
    <button @click="aTob">父页面A-->子页面B</button>
  </div>
</template>

<script>
export default {
  data () {
    return {
      children: []
    }
  },
  methods: {
    openPage () {
      const {href} = this.$router.resolve({name: 'B'})
      const child = window.open(href)
      this.children.push(child)
    },
    aTob () {
      // 用.closed属性过滤掉已经被关闭的 Tab 窗口
      this.children = this.children.filter(w => !w.closed)
      this.children.forEach(w => w.postMessage('----testData----'))
    }
  }
}
</script>

子页面B

<template>
  <div>这是子页面B</div>
</template>

<script>
export default {
  mounted () {
    window.addEventListener('message', (data) => {
      console.log(data, data.data)
    })
  },
  beforeDestroy () {
    window.removeEventListener('message')
  },
  methods: {
  }
}
</script>
子页面B-->父页面A

父页面A

<template>
  <div>
    <div>这是父页面A</div>
    <button @click="openPage">打开子页面B</button>
  </div>
</template>

<script>
export default {
  mounted () {
    window.addEventListener('message', (data) => {
      console.log(data, data.data)
    })
  },
  beforeDestroy () {
    window.removeEventListener('message')
  },
  methods: {
    openPage () {
      const {href} = this.$router.resolve({name: 'B'})
      window.open(href)
    }
  }
}
</script>

子页面B

<template>
  <div>
    <div>这是子页面B</div>
    <button @click="bToa">父页面A-->子页面B</button>
  </div>
</template>

<script>
export default {
  methods: {
    bToa () {
      window.opener.postMessage('----testData----')
    }
  }
}
</script>

其它方式的等用上了继续补充

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容