← 返回完整题库
JavaScript中等

需要在本地实现一个聊天室,多个tab页相互通信,不能用websocket,你会怎么做?

参考答案

方案一:BroadcastChannel(首选)

const ch = new BroadcastChannel('chat');
ch.postMessage({ user, text, ts });
ch.onmessage = e => render(e.data);

同源多 tab 直接广播,简单高效。

方案二:localStorage + storage 事件

写入 localStorage.setItem('msg', JSON.stringify({...})),其他 tab 监听 storage 事件(同源、不在写入的 tab 触发)。注意清理旧值与并发覆盖。

方案三:SharedWorker

多 tab 共享一个 Worker 作为消息中枢,通过 port 转发,可维护在线列表。

方案四:Service Worker

postMessage 中转;或用 IndexedDB 做持久化消息 + 轮询。

补充:storage 有大小限制且同步阻塞;BroadcastChannel 兼容性良好(IE 除外)。

本题来自 计算机知识面试题库,共 921 道题。