BroadcastChannel实现浏览器内多个标签页(.html)之间的通信

tab窗口通讯

简介

BroadcastChannel是一个Web API,用于在浏览器的不同窗口、标签页或者甚至不同的浏览器实例之间建立通信。它允许在同一个origin(来源)下的不同上下文之间发送数据,例如在同一个域名下的不同页面之间进行通信。

一、基本使用

  • 创建频道
const channel = new BroadcastChannel('id_a');
  • 发送信息
channel.postMessage('发送消息xxxxxx');
  • 接收消息
channel.onmessage = function(event) {
	console.log('接收信息 ', event.data);
};
  • 关闭频道
channel.close();

二、使用示例

  • 发送界面
<div>
    <input type="text" placeholder="请输入内容">
    <button onclick="handleSend()">发送消息</button>
</div>

<script>
    const channel = new BroadcastChannel('id_a');

    function handleSend() {
        let input = document.querySelector('input');

        if (input.value) channel.postMessage(input.value);
    }
</script>

  • 接收界面
<script>
    const channel = new BroadcastChannel('id_a');

    channel.onmessage = function (event) {
        let body = document.querySelector('body');

        body.textContent = event.data;
    };
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值