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

相关推荐
集成显卡18 小时前
Bun v1.3.6 发布:内置 Tarball 归档支持、JSONC 解析、Bundle 分析增强等重磅更新!
javascript·新版本·bun.js
奔跑的web.18 小时前
TypeScript Enum 类型入门:从基础到实战
前端·javascript·typescript
盐真卿18 小时前
python2
java·前端·javascript
kgduu19 小时前
js之表单
开发语言·前端·javascript
摘星编程21 小时前
React Native for OpenHarmony 实战:Picker 选择器组件详解
javascript·react native·react.js
摘星编程21 小时前
React Native for OpenHarmony 实战:VirtualizedList 虚拟化列表
javascript·react native·react.js
摘星编程1 天前
React Native for OpenHarmony 实战:RefreshControl 下拉刷新组件
javascript·react native·react.js
鸣弦artha1 天前
Flutter框架跨平台鸿蒙开发——Extension扩展方法
android·javascript·flutter
筱歌儿1 天前
TinyMCE-----word表格图片进阶版
开发语言·javascript·word
Ama_tor1 天前
obsidian进阶の插件系列|Templater从小白到菜鸟
javascript·markdown·插件·obsidian