每日一练:通过广播信道实现跨页面通信

发布时间 2023-11-15 10:34:27作者: 菜鸟小何

利用广播通道实现标签页通信

1. 什么是广播通道

广播通道是一种新的浏览器原生API,它可以让你在同源的标签页之间传递消息。这个API的目的是为了让开发者可以在不同的标签页之间共享数据,而不需要使用LocalStorage或者其他的存储方式。

2. 广播通道的使用

2.1 创建广播通道

const channel = new BroadcastChannel('test_channel');

2.2 发送消息

channel.postMessage('Hello World');

2.3 接收消息

channel.onmessage = function (ev) {
  console.log(ev.data);
}

2.4 关闭广播通道

channel.close();

3. 广播通道的兼容性

支持的浏览器:
桌面端:Chrome、Firefox、Safari、Edge、Opera等主流浏览器支持广播通道 API。
移动端:在移动浏览器中,Android 的 Chrome 和部分其他浏览器也提供支持。iOS 上的 Safari 也支持这一特性。
部分限制:
IE 和旧版浏览器:Internet Explorer 不支持广播通道 API,旧版的浏览器也可能存在兼容性问题。
跨域限制:跨域问题可能会限制通道的使用,需要遵循同源策略或考虑跨域通信的安全性措施。

4. 广播通道的应用场景

4.1 多标签页之间的通信

// tab1
const channel = new BroadcastChannel('test_channel');
channel.postMessage('Hello World');
// tab2
const channel = new BroadcastChannel('test_channel');
channel.onmessage = function (ev) {
  console.log(ev.data);
}

4.2 多窗口之间的通信

// window1
const channel = new BroadcastChannel('test_channel');
channel.postMessage('Hello World');
// window2
const channel = new BroadcastChannel('test_channel');
channel.onmessage = function (ev) {
  console.log(ev.data);
}

4.3 多iframe之间的通信

// iframe1
const channel = new BroadcastChannel('test_channel');
channel.postMessage('Hello World');
// iframe2
const channel = new BroadcastChannel('test_channel');
channel.onmessage = function (ev) {
  console.log(ev.data);
}

4.4 多浏览器之间的通信

// browser1
const channel = new BroadcastChannel('test_channel');
channel.postMessage('Hello World');
// browser2
const channel = new BroadcastChannel('test_channel');
channel.onmessage = function (ev) {
  console.log(ev.data);
}

4.5 多域名之间的通信

// domain1
const channel = new BroadcastChannel('test_channel');
channel.postMessage('Hello World');
// domain2
const channel = new BroadcastChannel('test_channel');
channel.onmessage = function (ev) {
  console.log(ev.data);
}

5. 广播通道的注意事项

5.1 广播通道的关闭

广播通道的关闭是一个很重要的问题,因为如果不关闭广播通道,那么会导致内存泄漏。广播通道的关闭有两种方式,一种是调用close方法,另一种是调用terminate方法。

// close
channel.close();
// terminate
channel.terminate();

5.2 广播通道的消息大小

广播通道的消息大小是有限制的,目前不同浏览器的限制不一样,但是一般都是在1MB左右。如果超过了这个限制,那么消息就会被丢弃。

5.3 广播通道的消息类型

广播通道的消息类型是有限制的,目前只支持字符串、数字、布尔值、对象、数组、Blob、File、ArrayBuffer、SharedArrayBuffer、ImageData、ArrayBufferView、DataView、Map、Set、Date、RegExp、Error、Promise、URL、URLSearchParams、USVString、ReadableStream、WritableStream、TransformStream、MessagePort、ImageBitmap、BigInt、BigInt64Array、BigUint64Array、Float32Array、Float64Array、Int8Array、Int16Array、Int32Array、Uint8Array、Uint16Array、Uint32Array、Uint8ClampedArray这些类型。