reference
I. Cross-page communication between homologous pages
1. BroadCast Channel
A BroadCast Channel can help us create a communication Channel for broadcasting. When all pages listen for messages on the same channel, messages sent by one page are received by all the other pages.
To create a channel branded AlienZHOU:
const bc = new BroadcastChannel('AlienZHOU');
Copy the code
Individual pages can listen for messages to be broadcast via onMessage:
bc.onmessage = function (e) {
const data = e.data;
const text = '[receive] ' + data.msg + '- the TAB' + data.from;
console.log('[BroadcastChannel] receive message:', text);
};
Copy the code
To send a message, simply call the postMessage method on the instance:
bc.postMessage(mydata);
Copy the code
2. Service Worker
The Service Worker is a Worker that can run in the background for a long time and can realize two-way communication with the page. Service workers between multiple page sharing can be shared, and the broadcast effect can be realized by taking the Service Worker as the message processing center (central station).
(1) Register Service Worker on the page:
/ / page
navigator.serviceWorker.register('.. /util.sw.js').then(function () {
console.log('Service Worker registered successfully ');
});
Copy the code
(2) In… /util.sw.js, in the Service Worker script:
/ *.. / uti.sw. js Service Worker logic */
self.addEventListener('message'.function (e) {
console.log('service worker receive message', e.data);
e.waitUntil(
self.clients.matchAll().then(function (clients) {
if(! clients || clients.length ===0) {
return;
}
clients.forEach(function (client) { client.postMessage(e.data); }); })); });Copy the code
We listen for the Message event in the Service Worker and get the message sent by the page (called client from the perspective of the Service Worker). We then call self.clients.matchall () to retrieve all pages that are currently registered with the Service Worker and send a message to the page by calling the postMessage method of each client (page). This notifies the other pages of messages received from one Tab page.
After processing the Service Worker, we need to listen for the message sent by the Service Worker on the page:
/ / page
navigator.serviceWorker.addEventListener('message'.function (e) {
const data = e.data;
const text = '[receive] ' + data.msg + '- the TAB' + data.from;
console.log('[Service Worker] receive message:', text);
});
Copy the code
Finally, when messages need to be synchronized, the Service Worker’s postMessage method can be called:
/* Page logic */
navigator.serviceWorker.controller.postMessage(mydata);
Copy the code
3. LocalStorage
When LocalStorage changes, the storage event is triggered. With this feature, we can write a message to a LocalStorage when sending it. Then in each page, you can receive notifications by listening for storage events.
// Add to each page to listen for changes in localstorage
window.addEventListener('storage'.function (e) {
if (e.key === 'ctc-msg') {
const data = JSON.parse(e.newValue);
const text = '[receive] ' + data.msg + '- the TAB' + data.from;
console.log('[Storage I] receive message:', text); }});Copy the code
When a page needs to send a message, just use the setItem method:
mydata.st = +(new Date);
window.localStorage.setItem('ctc-msg'.JSON.stringify(mydata));
Copy the code
Notice one detail: we’ve added a.st property to myData that takes the current millisecond timestamp. This is because a storage event is emitted only when the value actually changes.
The subtotal
BroadCast channels, Service workers, and LocalStorage are all BroadCast formats: one page sends message notifications to a central station, which in turn notifies each page.
Next comes shared storage + polling mode.
4. Shared Worker
Ordinary workers operate independently and their data are not connected to each other. Shared workers registered with multiple tabs can realize data sharing.
The problem of Shared Worker in realizing cross-page communication is that it cannot actively notify all pages, so we use polling to pull the latest data. Here’s the idea:
Let the Shared Worker support two types of messages. One is POST, in which the Shared Worker saves the data after receiving it. The other is GET. After receiving the message, the Shared Worker will send the saved data to the page where it is registered via postMessage. That is, the page uses get to actively get (synchronize) the latest news.
Specific references are used.
5. IndexedDB
In addition to sharing data with Shared workers, there are other “global” (cross-page) storage solutions that can be used. Such as IndexedDB or cookie.
Similar to the Shared Worker scheme, the message sender stores the message in IndexedDB. Recipients (for example, all pages) poll to get the latest information.
Next, in A multi-tab scenario, we might move from Tab A to Tab B; After A while, when we switch from Tab B back to Tab A, we want to synchronize the information from the previous actions in Tab B. At this point, in fact, only in Tab A listening visibilitychange event, to do A synchronization of information.
6. window.open + window.opener
Use references in detail.
2. Communication between non-homologous pages
For example, the reference
1. postMessage
2. webSocket
WebSocket is a protocol for full duplex communication over a single TCP connection provided by HTML5.