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()中的使用

相关推荐
端庄的战斗机1 小时前
javascript 设计模式(文章很长,请自备瓜子,水果和眼药水)
开发语言·javascript·设计模式
前端毕业班4 小时前
uni-app 小程序支持 teleport 了
前端·javascript·vue.js
东风破_4 小时前
LLM 为什么记不住你?无状态、messages 和上下文管理
javascript·人工智能
Hilaku5 小时前
前端架构师的克制:什么时候该坚决对新技术说不?
前端·javascript·程序员
古夕5 小时前
多应用同域部署下 Favicon 异常问题排查与治理
前端·javascript
逗逗豆巴吧6 小时前
WPS 加载项中实现当前文档直接上传
前端·javascript·ecmascript 6
妙码生花6 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(二十一):网络请求封装优化
前端·javascript·vue.js
用户11481867894846 小时前
普通Fetch、Fetch流式、Axios、SSE:谁才是流式输出的正确操作?
前端·javascript
谷哥的小弟6 小时前
TypeScript数组类型
javascript·typescript
2603_955279707 小时前
C++23新特性在CLion中的实战体验
前端·javascript·c++23