SharedWorkers 绝对更适合复杂的情况,将 BroadcastChannel 视为一对多的简单通知发送者。
它无法传输数据——那么哪个接收者应该成为所有者?— 因此,除了 Blob(它们只是没有自己的数据的小型包装器)的情况外,通过 BroadcastChannel 传递数据意味着它必须由所有接收器完全反序列化,而不是最高效的方式。
所以我不确定你需要发送什么样的数据,但如果它是通常应该可以传输的大数据,那么可能更喜欢 SharedWorker。
但是,如果您的数据不被传输,一种解决方法是创建一个新的 BroadcastChannel,只有您的两个上下文会监听。
现场演示
在页面 A 中:
const common_channel = new BroadcastChannel( "main" );
const uuid = "private-" + Math.random();
common_channel.postMessage( {
type: "gimme the data",
from: "pageB",
respondAt: uuid
} );
const private_channel = new BroadcastChannel( uuid );
private_channel.onmessage = ({data}) => {
handleDataFromPageB(data);
private_channel.close();
};
在 B 页:
const common_channel = new BroadcastChannel( "main" );
common_channel.onmessage = ({ data }) => {
if( data.from === "pageB" && data.type === "gimme the data" ) {
const private_channel = new BroadcastChannel( data.respondAt );
private_channel.postMessage( the_data );
private_channel.close();
}
};
关于为什么不能ports
在 BroadcastChannels 上触发 MessageEvent 的值,这是因为 MessagePorts 必须被传输,但正如我们已经说过的,BroadcastChannels 不能进行传输。
为什么没有source
,这可能是因为正如您所料,它应该是一个 WindowProxy 对象,但是 WorkerContexts 也可以将消息发布到 BroadcastChannels,并且它们没有实现该接口(例如,它们的postMessage
方法根本不会做同样的事情而不是 WindowContext)。