JavaScript API MessageChannel 多线程异步通信

MessageChannel 是一种用于在不同线程之间进行通信的 JavaScript API。它允许创建一个双向的通信通道,用于发送和接收消息。MessageChannel 可以在主线程和 Web Worker 之间建立通信,也可以在主线程和 Service Worker 之间建立通信。

使用 MessageChannel,开发者可以创建一个通信端口,通过端口发送消息,并监听来自另一个端口的消息。

  • 对于主线程和 Web Worker 之间的通信,可以使用 postMessage() 方法发送消息,使用 onmessage 事件监听接收到的消息。
  • 对于主线程和 Service Worker 之间的通信,可以使用 Service WorkerpostMessage() 方法发送消息,使用 Navigator 对象的 onmessage 事件监听接收到的消息。

代码示例

在下面的代码块中,你会看到一个由 MessageChannel 构造函数创建的新 Channel. 当 IFrame 被加载后,我们使用 MessagePort.postMessage 把 port2 和一条消息一起发送给 IFrame. 然后 handleMessage 回调响应 IFrame 发回的消息(使用 MessagePort.onmessage),并把它渲染到页面段落中。MessageChannel.port1 用来监听,当消息到达时,会进行处理。

<h1>Channel messaging demo</h1>
<p class="output">A message from the iframe in page2.html</p>
<iframe src="page2.html" width="480" height="320"></iframe>
<script>
	const channel = new MessageChannel();
	const output = document.querySelector(".output");
	const iframe = document.querySelector("iframe");
    
	// Wait for the iframe to load
	iframe.addEventListener("load", onLoad);
    
	function onLoad() {
		// Listen for messages on port1
		channel.port1.onmessage = onMessage;
		// Transfer port2 to the iframe
		iframe.contentWindow.postMessage(
		  "A message from the index.html page!",
		  "*",
		  [channel.port2]
		);
	}
    
		// Handle messages received on port1
		function onMessage(e) {
			console.log(e)
			output.innerText = e.data;
		}
</script>
<!-- page2.html -->
<p class="output">A message from the index.html page!</p>
<script>
	const output = document.querySelector(".output");
    
	window.addEventListener("message", onMessage);
    
	function onMessage(e) {
		output.innerText = e.data;
		// Use the transferred port to post a message to the main frame
		e.ports[0].postMessage("A message from the iframe in page2.html");
          }
</script>

总结

MessageChannel 提供了一种可靠、高效的异步(宏任务)通信方式,可以用于多个线程之间的数据传输和协作,特别适用于复杂的交互和并行处理场景。使用 MessageChannel 可以方便地实现一些功能,例如主线程和 Web Worker 之间的任务分发、主线程和 Service Worker 之间的数据同步等。

  • 10
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值