ServiceWorker on the Internet is generally used to do PWA, this is not introduced here, if you need to know, baidu

Principle:

ServiceWorker is a page-independent, browser-level thread

ServiceWorker threads can communicate with pages via addEventListener(‘message’,postMessage)

The serviceWorker thread retrieves all browser Windows controlled by this thread self.clients.matchall ()

Code parsing

  1. First the page is initialized when initializedserviceWorker:
navigator.serviceWorker
      .register('serviceWorker.js', {
        scope: '/',
      })
      .then(function(registration) {...Copy the code
  1. Each page is notified when enteredserviceWorkerA new page opens and listensserviceWorkerThe information.

Page code:

navigator.serviceWorker.controller.postMessage({
    type: 'closeOtherClient',
 })

navigator.serviceWorker.addEventListener('message'.function(event) {
    if (event.data.oprType && event.data.oprType === 'close') {
      disconnectCBS.forEach(cb= > cb())
    }
})
Copy the code
  1. serviceWorker.jscode

When serviceWorker receives a new window opening signal, it notifies all other pages to execute a shutdown code (for example, a popup on the page prompts the user that your account has been logged in elsewhere).

this.addEventListener('message'.function(event) {
  const senderId = event.source ? event.source.id : 'unknow'

  if (event.data.type === 'closeOtherClient') {
    self.clients.matchAll().then(function(clients) {
      if (clients && clients.length) {
        clients.forEach(function(client) {
          if(senderId ! == client.id) { client.postMessage({oprType: 'close'})}})}})Copy the code

— — — — — — — — — — — — — — — — — — — — – update — — — — — — — — — — — — — — — — — — — — — — — — — — —

In fact, recently found a simpler solution: localStorage

The serviceWorker above addresses only one problem: cross-tab communication within the browser

The principle of cross-Tab communication with localStorage is as follows: When localstorage is modified, an event: storage is triggered in the browser TAB under the domain name. You can use window.addEventListener to listen to this event

Therefore, if you want to notify other tabs, directly change localStorage, other tabs listen for this event can be processed, thus completing the cross-tab communication

Other methods

Of course, you can also set a timer poll localstorage or even cookies, etc., in a TAB to change the localstorage, other tabs in the poll found that the value changed can be processed. But that makes it look low