js跨标签页通信

一、为什么要跨标签页通信

在web开发中,有时会有这样的情况,A页面中打开了B页面,B页面中操作了一些内容,再回到A页面时,需要看到更新后的内容。这种场景在电商、支付、社交等领域经常出现。

二、实现跨标签页通信的几种方式

2.1 localStorage

打开A页面,可以看到localStorage和sessionStorage中都存储了testA:

B页面中,可以获取到localStorage,但是无法获取到sessionStorage:

2.2 BroadcastChannel

BroadcastChannel允许同源下浏览器不同窗口订阅它,postMessage方法用于发送消息,message事件用于接收消息。

A页面:

js 复制代码
      const bc = new BroadcastChannel('test')

      bc.postMessage('不去上班行吗?')

B页面:

js 复制代码
      const bc = new BroadcastChannel('test')

      bc.onmessage = (e) => {
        console.log(e)
      }

2.3 postMessage(跨源通信)

2.3.1 iframe跨域数据传递

parent.html

js 复制代码
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title></title>
  </head>
  <body>
    <h1>主页面</h1>
    <iframe id="child" src="http://10.7.9.69:8080"></iframe>
    <div>
      <h2>主页面跨域接收消息区域</h2>
      <div id="message"></div>
    </div>
  </body>
  <script>
    // 传递数据到子页面
    window.onload = function () {
      // 第二个参数表示哪个窗口可以接收到消息
      document.getElementById('child').contentWindow.postMessage('不上班行不行', 'http://10.7.9.69:8080')
    }
    // 接受子页面传递过来的数据
    window.addEventListener('message', function (event) {
      document.getElementById('message').innerHTML = '收到' + event.origin + '消息:' + event.data
    })
  </script>
</html>

App.vue

js 复制代码
<template>
  <div class="app">
    <div id="message"></div>
  </div>
</template>
<script>
export default {
  created() {
    // 接收父页面传过来的数据
    window.addEventListener('message', function (event) {
      // 处理addEventListener执行两次的情况,避免获取不到data
      // 因此判断接收的域是否是父页面
      console.log('event', event)
      if (event.origin.includes('http://127.0.0.1:5501')) {
        document.getElementById('message').innerHTML = '收到' + event.origin + '消息:' + event.data
        // 把数据传递给父页面  window.parent === top
        window.parent.postMessage('不上班你养我啊', 'http://127.0.0.1:5501')
      }
    })
  },
}
</script>

注:

  1. http://127.0.0.1:5501/ 是使用 Open with Live Server打开后的地址
  2. http://10.7.9.69:8080/ 是启动vue后的地址

2.3.2 postMessage在window.open()中的使用

相关推荐
摘星编程23 分钟前
React Native for OpenHarmony 实战:ImageBackground 背景图片详解
javascript·react native·react.js
摘星编程1 小时前
React Native for OpenHarmony 实战:Alert 警告提示详解
javascript·react native·react.js
Joe5562 小时前
vue2 + antDesign 下拉框限制只能选择2个
服务器·前端·javascript
WHS-_-20222 小时前
Tx and Rx IQ Imbalance Compensation for JCAS in 5G NR
javascript·算法·5g
摘星编程2 小时前
React Native for OpenHarmony 实战:GestureResponderSystem 手势系统详解
javascript·react native·react.js
lili-felicity2 小时前
React Native for OpenHarmony 实战:加载效果的实现详解
javascript·react native·react.js·harmonyos
济6172 小时前
linux 系统移植(第六期)--Uboot移植(5)--bootcmd 和 bootargs 环境变量-- Ubuntu20.04
java·前端·javascript
lili-felicity3 小时前
React Native for OpenHarmony 实战:Easing 动画完全指南
javascript·react native·react.js
持续前行3 小时前
vscode 中找settings.json 配置
前端·javascript·vue.js
JosieBook3 小时前
【Vue】11 Vue技术——Vue 中的事件处理详解
前端·javascript·vue.js