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

相关推荐
hamburgerDaddy136 分钟前
从零开始用react + tailwindcs + express + mongodb实现一个聊天程序(二)
前端·javascript·mongodb·react.js·前端框架·express
爱上妖精的尾巴42 分钟前
3-1 WPS JS宏工作簿的新建与保存(批量新建工作簿)学习笔记
开发语言·javascript·笔记·js·wps
bin91531 小时前
DeepSeek 助力 Vue 开发:打造丝滑的文本输入框(Text Input)
前端·javascript·vue.js·前端框架·ecmascript·deepseek
pixle01 小时前
Three.js 快速入门教程【六】相机控件 OrbitControls
前端·javascript·3d
前端南玖2 小时前
小程序如何实现跨页面通信
javascript·小程序·taro
Alang3 小时前
Antd table 无限滚动+懒加载
前端·javascript·react.js
jay丿3 小时前
Django简介
javascript
想尝一尝被打赏的味道4 小时前
uniapp在app下使用mqtt协议!!!支持vue3
javascript·vue.js·uni-app
cc.ChenLy4 小时前
vue框架后遗症∶被遗忘的dom操作
javascript·vue.js
Python私教4 小时前
Flutter 实现抖音风格底部导航栏
android·开发语言·javascript