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

相关推荐
kyriewen5 小时前
程序员连夜带团队跑路,省了23万:这AI太贵,真的用不起了
前端·javascript·openai
我叫黑大帅8 小时前
为什么需要 @types/react?解决“无法找到模块 react 的声明文件”报错
前端·javascript·面试
之歆8 小时前
DAY_21JavaScript 深度解析:数组(Array)与函数(Function)(一)
前端·javascript
爱上好庆祝9 小时前
学习js的第七天(wed APIs的开始)
前端·javascript·css·学习·html·css3
ooseabiscuit10 小时前
Laravel6.x核心优化与特性全解析
android·开发语言·javascript
哆啦A梦158811 小时前
20, Springboot3+vue3实现前台轮播图和详情页的设计
javascript·数据库·spring boot·mybatis·vue3
gogoing11 小时前
ESLint 配置字段说明
前端·javascript
Lkstar11 小时前
面试官让我手写 Promise.all / Promise.race / Promise.allSettled,我直接水灵灵地写出来了
javascript·面试
gogoing11 小时前
webpack 的性能优化
前端·javascript
gogoing11 小时前
Node.js 模块查找策略(require 完整流程)
javascript·node.js