BroadcastChannel:跨标签页通信

目前浏览器跨标签页通信的方式有很多,比如:websocket、针对LocalStorage使用window.onstorage、window.postmessage。
本文将用BroadcastChannel实现同一域名下两个标签页间消息的收和发

一、全局创建通信通道

const channel = new BroadcastChannel('channel1');

二、发送消息与监听消息

const sendMsg = (type, msg) => {
  channel.postMessage({
    type,
    msg,
  });
};

const listen = (callback) => {
  channel.addEventListener('message', (e) => {
    console.log('eee', e);
    callback(e.data);
  });
}

三、应用

触发事件

const handleClick = () => {
  sendMsg('add', { name: '张三', age: 22 });
}

接受消息处理业务逻辑

listen((data) => {
  console.log('data', data);
  const { type, msg } = data;
  if (type === 'add') {
    const h1 = document.querySelector('h1');
    h1.append(`姓名:${msg.name}-年龄:${msg.age}`);
  }
});

演示

使用Live Server启动本地演示项目,两个标签页打开同一个页面,一个发一个收

channel

源码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script src="./channel.js"></script>
  <script src="./index.js"></script>
  <button onclick="handleClick(event)">发送</button>
  <h1></h1>
</body>
</html>
// channel.js

const channel = new BroadcastChannel('channel1');

const sendMsg = (type, msg) => {
  channel.postMessage({
    type,
    msg,
  });
};

const listen = (callback) => {
  channel.addEventListener('message', (e) => {
    console.log('eee', e);
    callback(e.data);
  });
}
// index.js

listen((data) => {
  console.log('data', data);
  const { type, msg } = data;
  if (type === 'add') {
    const h1 = document.querySelector('h1');
    h1.append(`姓名:${msg.name}----年龄:${msg.age}`);
  }
});

const handleClick = () => {
  sendMsg('add', { name: '张三', age: 22 });
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值