HTML5 API 多端通信桥 MessageChannel 技术
warning:
这篇文章距离上次修改已过449天,其中的内容可能已经有所变动。
在HTML5中,MessageChannel API允许我们在同一个文档的不同脚本之间建立一个新的通信通道。这个通道是双向的,可以发送多个消息。
以下是一个简单的例子,展示如何使用MessageChannel来在两个脚本之间发送消息:
// 主线程中
const createChannel = () => {
let channel = new MessageChannel();
// 设置接收消息的监听器
channel.port1.onmessage = function(e) {
console.log('接收到消息: ', e.data);
};
// 在worker中使用port2发送消息
const worker = new Worker('worker.js');
worker.postMessage({ hello: 'world' }, [channel.port2]);
};
createChannel();在另一个文件(worker.js)中,我们可以这样使用MessageChannel:
// worker.js 中
self.onmessage = function(e) {
const port = e.ports[0];
if (port) {
port.postMessage('你好,这是worker发送的消息!');
// 当不再需要通信时,关闭通道
port.start();
port.close();
}
};在这个例子中,我们在主线程中创建了一个MessageChannel,然后将其一个端口(port1)用于监听消息,另一个端口(port2)则传递给了一个Worker。在Worker中,我们接收到port2并用它发送一条消息。当通信完成后,我们通过调用port.close()来关闭通信通道。
评论已关闭