选项卡或窗口之间的通信 - Communication between tabs or windows

问题:

I was searching for a way how to communicate between multiple tabs or windows in a browser (on the same domain, not CORS ) without leaving traces.我正在寻找一种如何在浏览器中的多个选项卡或窗口(在同一个域上,而不是CORS 上)之间进行通信而不留下痕迹的方法。 There were several solutions:有几种解决方案:

  1. using the window object 使用窗口对象
  2. postMessage 留言
  3. cookies 饼干
  4. localStorage 本地存储

The first is probably the worst solution - you need to open a window from your current window and then you can communicate only as long as you keep the windows open.第一个可能是最糟糕的解决方案 - 您需要从当前窗口打开一个窗口,然后只有在保持窗口打开的情况下才能进行通信。 If you reload the page in any of the windows, you most likely lost the communication.如果您在任何窗口中重新加载页面,您很可能会丢失通信。

The second approach, using postMessage, probably enables cross-origin communication, but it suffers the same problem as the first approach.使用 postMessage 的第二种方法可能支持跨域通信,但它遇到与第一种方法相同的问题。 You need to maintain a window object.您需要维护一个窗口对象。

The third way, using cookies, store some data in the browser, which can effectively look like sending a message to all windows on the same domain, but the problem is that you can never know if all tabs read the "message" already or not before cleaning up.第三种方式,使用 cookie,在浏览器中存储一些数据,这可以有效地看起来像向同一域中的所有窗口发送消息,但问题是您永远无法知道所有选项卡是否已经阅读了“消息”在清理之前。 You have to implement some sort of timeout to read the cookie periodically.您必须实现某种超时才能定期读取 cookie。 Furthermore you are limited by maximum cookie length, which is 4 KB.此外,您受到最大 cookie 长度的限制,即 4 KB。

The fourth solution, using localStorage, seemed to overcome the limitations of cookies, and it can be even listen-to using events.第四个方案,使用localStorage,似乎克服了cookies的限制,甚至可以使用事件监听。 How to use it is described in the accepted answer.已接受的答案中描述了如何使用它。

In 2018, the accepted answer still works, but there is a newer solution for modern browsers, to use BroadcastChannel.在 2018 年,接受的答案仍然有效,但现代浏览器有一个更新的解决方案,使用 BroadcastChannel。 See the other answer for a simple example describing how to easily transmit message between tabs by using BroadcastChannel.有关描述如何使用 BroadcastChannel 在选项卡之间轻松传输消息的简单示例,请参阅其他答案。


解决方案:

参考一: https://stackoom.com/question/1uS8D
参考二: Communication between tabs or windows
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章