選項卡或窗口之間的通信 - 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章