Browser communication between multiple tabs or windows mainly refers to the communication among multiple pages from the same origin. The main methods include local storage communication, Web Worker communication, and Web Socket communication.
Communication is achieved through the shared strategy of local storage for same-origin pages. The main methods include localStorage, cookie, and indexedDB. It is important to note that sessionStroage is effective within the same session. According to MDN, it is mentioned that when clicking a link or opening a new tab using window.open, they belong to the same session. The new tab will inherit the sessionStroage of the parent session. However, opening a new tab always initializes a new session, even if they are of the same origin, they do not belong to the same session.
// Page Bwindow.addEventListener("storage",function(e){ console.log(e);})// The onstorage event// It will only be triggered when localStorage is modified by a non-current page. Modifying localStorage from the current page will not trigger the listening function.// The listening function will only be triggered when modifying the original data value. It will not be triggered if the new value is the same as the original value.
In HTML5, Web Worker can be divided into two different types of threads, one is a dedicated worker, and the other is a shared worker.
A dedicated worker can be created directly using new Worker(), and it is exclusive to the current page.
A SharedWorker can be shared by multiple windows, tabs, and iframes, but they must ensure that these pages are from the same origin.
Using Web Socket to transfer data through the server can achieve communication between browser windows, but it consumes considerable server resources. WebSocket is a full-duplex communication protocol over a single TCP connection provided from HTML5. It simplifies data exchange between clients and servers, allowing the server to push data to the client actively. In the WebSocket API, the browser and the server only need to perform a handshake once, and then a persistent connection is established, enabling bidirectional data transfer. During the handshake phase, the HTTP protocol is used, and additional header information is included in the normal HTTP message, with the Upgrade: WebSocket header indicating a protocol upgrade request.
It is built on top of the TCP protocol and belongs to the application layer like HTTP.
It can send both text and binary data.
Its data format is lightweight, with minimal performance overhead and high communication efficiency.
There is no same-origin policy, and the client can communicate with any server.
The protocol identifier is ws, and if encrypted transmission is used, it is wss.