最近,我在Chrome中使用API BroadcastChannel时遇到了一个奇怪的问题。我有一个选项卡需要来自其他选项卡的数据,所以我使用BroadcastChannel将其存档。
当用户点击该按钮时,它将触发一个postMessage
到正在收听相同BroadcastChannel 的目的地选项卡
const sendData = data => {
const broadcast = new BroadcastChannel('viewDataChannel')
broadcast.postMessage(data);
};
// ...
<Button onClick={data => sendData(data)}>Send data</Button>
// Receiver
const broadcast = new BroadcastChannel('viewDataChannel');
broadcast.postMessage = data => setData(data);
一切都很好,直到不行。在生产过程中,用户经常点击按钮,点击几次(可能10次(后,Chrome就冻结了(RAM和CPU使用率高,我的应用程序也冻结了(,我不得不杀死浏览器并重新启动它
我通过将代码create BroadcastChannel实例移动到函数外部来修复它,只是第一次创建它,但我做了很多研究,仍然没有发现任何与创建许多相同的BroadcastChannel相关的东西会导致浏览器冻结
有人知道BroadcastChannel的工作原理并解释为什么会发生这种情况吗?
问题出在sendData
方法中:
const sendData = data => {
const broadcast = new BroadcastChannel('viewDataChannel')
broadcast.postMessage(data);
};
通过在此处调用new BroadcastChannel
,您将尝试在每次发送数据时创建另一个实例。相反,如果将其从sendData
函数中移出,则在每次调用sendData
:时都将重用相同的BroadcastChannel
const broadcast = new BroadcastChannel('viewDataChannel')
const sendData = data => {
broadcast.postMessage(data);
};