js实现浏览器不同页签之间通信

一. 使用BroadcastChannel

const sendMsg = new BroadcastChannel('logout_channel')
sendMsg.postMessage('清除缓存')
onMsg.onmessage = async (event) => {
   console.log('event清除缓存', event.data)
}

二. 使用SharedWorker

1.创建一个SharedWorker实例,并在其中编写处理消息的代码。

// shared-worker.js
onconnect = function(e) {
  var port = e.ports[0];
  
  port.onmessage = function(e) {
    var message = e.data;
    // 在这里处理接收到的消息
  };
  
  port.start();
};
  1. 在多个窗口中分别创建SharedWorker的端口,并发送消息。

    // window1.js
    var worker = new SharedWorker('shared-worker.js');
    var port = worker.port;

    port.onmessage = function(e) {
    var message = e.data;
    // 在这里处理接收到的消息
    };

    port.postMessage('Hello from window1!');

    // window2.js
    var worker = new SharedWorker('shared-worker.js');
    var port = worker.port;

    port.onmessage = function(e) {
    var message = e.data;
    // 在这里处理接收到的消息
    };

    port.postMessage('Hello from window2!');

  2. 在SharedWorker中处理接收到的消息,并向所有连接的窗口发送消息。

    // shared-worker.js
    onconnect = function(e) {
    var port = e.ports[0];

    port.onmessage = function(e) {
    var message = e.data;
    // 在这里处理接收到的消息

     // 向所有连接的窗口发送消息
     e.source.postMessage('Hello from SharedWorker!');
    

    };

    port.start();
    };

相关推荐
红色石榴2 分钟前
Qt中文乱码解决
开发语言·qt
Htht1114 分钟前
【Qt】实现模拟触摸屏 上下滑动表格 的两种方式
开发语言·qt
会蹦的鱼4 分钟前
React学习day07-ReactRouter-抽象路由模块、路由导航、路由导航传参、嵌套路由、默认二级路由的设置、两种路由模式
javascript·学习·react.js
A 八方4 分钟前
Python MongoDB
开发语言·python·mongodb
sz66cm2 小时前
Python基础 -- 使用Python实现ssh终端并实现数据处理与统计功能
开发语言·python·ssh
liangbm33 小时前
MATLAB系列02:MATLAB基础
开发语言·数据结构·笔记·matlab·教程·工程基础·高级绘图
change95134 小时前
PHP纯离线搭建(php 8.1.7)
开发语言·php
DT——4 小时前
Vite项目中eslint的简单配置
前端·javascript·代码规范
福鸦5 小时前
详解c++:new和delete
开发语言·c++
qq_172805595 小时前
Go Testify学习与使用
开发语言·golang·go