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 A
localStorage.setItem('msg', Math.random());
// Page B
window.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.
// Page A
document.cookie = "msg=1;path=/";
// Page B
function getCookie(key){
var cookies = {};
document.cookie.replace(/\s*/g,"").split(";").forEach((v) => {
let unit = v.split("=");
cookies[unit[0]] = unit[1];
})
return cookies[key];
}
setInterval(() => {
console.log(getCookie("msg"));
}, 1000);
// Page A
var db = null;
var request = indexedDB.open("message");
request.onsuccess = (e) => db = e.target.result;
request.onupgradeneeded = function(event) {
db = event.target.result;
if (!db.objectStoreNames.contains('message')) {
db.createObjectStore('message', { keyPath: 'key' });
}
};
function setData(data){
var transaction = db.transaction(['message'], 'readwrite');
var store = transaction.objectStore(['message']);
var requestData = store.put({ key: "msg", info: data});
requestData.onsuccess = function(e) {
console.log(e.target.result);
};
};
setTimeout(() => setData(1),1000);
// Page B
var db = null;
var request = indexedDB.open("message");
request.onsuccess = (e) => db = e.target.result;
function readMsg(){
var transaction = db.transaction(['message']);
var objectStore = transaction.objectStore('message');
var requestResult = objectStore.get('msg');
requestResult.onsuccess = function(event) {
console.log(requestResult.result.info);
};
}
setTimeout(readMsg, 3000);
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.
// Page A
var worker = new SharedWorker('worker.js');
worker.port.start();
worker.port.postMessage(1);
// Page B
var worker = new SharedWorker('worker.js');
worker.port.start();
worker.port.onmessage = function(event){
console.log(event.data);
};
// worker.js
var portArr = [];
onconnect = function(e) {
var port = e.ports[0];
if(portArr.indexOf(port) === -1) portArr.push(port);
port.onmessage = function(e) {
portArr.forEach( v => {
v.postMessage(e.data);
})
}
}
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 likeHTTP
. - 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 iswss
.
https://github.com/WindrunnerMax/EveryDay
https://github.com/lmk123/blog/issues/66
https://www.cnblogs.com/cloud-/p/10713213.html
https://www.cnblogs.com/lalalagq/p/9921144.html