概述SharedWorker 可在多个页面间共享同一运行上下文,适合作为数据管道与协调中心。本文提供连接与消息分发示例。能力检测与连接const supportsSW = typeof SharedWorker === 'function';

function connectShared() {

if (!supportsSW) return null;

const sw = new SharedWorker('shared.js');

sw.port.start();

sw.port.postMessage({ type: 'hello' });

sw.port.onmessage = e => {

if (e.data.type === 'state') {

localStorage.setItem('shared-state', JSON.stringify(e.data.payload));

}

};

return sw.port;

}

SharedWorker 端消息分发const ports = [];

onconnect = e => {

const port = e.ports[0];

ports.push(port);

port.onmessage = ev => {

if (ev.data.type === 'hello') {

for (const p of ports) p.postMessage({ type: 'state', payload: { ts: Date.now() } });

}

};

};

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部