Several schemes to realize multi-label communication

1. BroadcastChannel

MDN:

The Broadcast Channel API enables simple communication between different browser Windows, tabs, frames, or iframe contexts (usually different pages on the same website) in the same source browser.

1) usage:

// Connect to the broadcast channel
var bc = new BroadcastChannel('test_channel');

// Send a message
bc.postMessage('This is a test message.');

// Receive the message
bc.onmessage = function (ev) { console.log(ev); }

// Disconnect the channel connection
bc.close()
Copy the code

2) Compatibility:

3) advantages:

Native interface, can be used directly; Simple interface, easy to use.

4) disadvantages:

The BroadcastChannel interface is not supported by Internet Explorer and Safari. If Internet Explorer and Safari are used, the BroadcastChannel interface cannot be used.

2. WebSocket

WebSocket scheme requires the cooperation of the back end. The page creates socket and communicates with the back end to realize the communication between the tabs. The implementation will not be described here.

Disadvantages:

Need back-end coordination, not convenient enough.

3. SharedWorker

MDN:

The SharedWorker ** interface represents a specific type of worker and can be accessed from several browsing contexts, such as Windows, iframes, or other workers. They implement an interface different from ordinary workers and have different global scope, SharedWorkerGlobalScope (en-US).

Note: For SharedWorker to connect to multiple different pages, the pages must be homologous (same protocol, host, and port).

1) usage:

let worker = new SharedWorker('sharedworkers.js');

// Pass the strat instruction to enable the port
worker.port.postMessage('start');

// Receive data from the child thread
worker.port.onmessage = function (val) { 
    timeDom.innerHTML = val.data 
}

// sharedworkers.js
let a = 0;
onconnect = function (e) { 
    // Get port via e.ports
    var port = e.ports[0]; 
    // port.onMessage listens for messages from the parent thread
    port.onmessage = function () { 
        // port.postMessage passes messages to the parent thread
        port.postMessage(a++) 
    } 
}
Copy the code

2) Compatibility:

3) advantages:

Worker runs in an independent thread, which is friendly to page performance and can perform large computation.

4) disadvantages:

A separate worker file is required; Debugging is more troublesome than js on the page; Poor compatibility, IE does not support it, Safari has supported it and may support it in the future, but it is not currently supported and unreliable.

4. window.postMessage

MDN:

The window.postMessage() method can safely implement cross-source communication. In general, scripts with two different pages can only communicate with each other if the page executing them is on the same protocol (usually HTTPS), port number (443 is the default value for HTTPS), and host (the module document.domain of the two pages is set to the same value). The window.postmessage () method provides a controlled mechanism to circumvent this limitation and is safe as long as it is used correctly.

In broad terms, a window can get a reference to another window (such as targetWindow = window.opener) and then distribute a MessageEvent message by calling the targetwindow.postMessage () method on the window. The window receiving the message is free to process this event (en-US) as needed. Arguments passed to window.postMessage(), such as message, are exposed to the window receiving the message through the message event object.

1) usage:

The sender:

/* * The domain name of window A is 
      
       . The following is the code under the script tag of window A: */
      

var popup = window.open(... popup details...) ;// If the popup is not blocked and the load is complete

// This line does not send a message, even assuming that the current page has not changed location (because the targetOrigin is not set correctly)
popup.postMessage("The user is 'bob' and the password is 'secret'"."https://secure.example.net");

// Assuming the current page does not change location, this statement will successfully add message to the send queue (targetOrigin is set correctly)
popup.postMessage("hello there!"."http://example.org");

function receiveMessage(event)
{
  Can we trust the sender of the message? (Maybe this sender is not the same page we originally opened).
  if(event.origin ! = ="http://example.org")
    return;

  // Event. source is the popup page we open with window.open
  // event.data is the message popup sends to the current page "Hi there yourself! the secret response is: rheeeeet!"
}
window.addEventListener("message", receiveMessage, false);

Copy the code

Receiver:

/* * popup domain is <http://example.org>, here is the code in the script tag: Function receiveMessage(event) {// Can we trust the source of the message? if (event.origin ! == "http://example.com:8080") return; // event.data is "Hello there!" // Assuming that you have verified the origin of the received message (which you should do at any time), a convenient way to do this is to send the event. Source // as a reply object, And make event.origin as targetOrigin event.source-postMessage (" Hi there yourself! the secret response " + "is: rheeeeet!" , event.origin); } window.addEventListener("message", receiveMessage, false);Copy the code

2) Compatibility:

3) advantages:

Good compatibility and security.

4) disadvantages:

You need to get handles of other Windows, such as open, opener and iframe, which cannot be used in other cases.

5. localStorage

LocalStorage can be shared between Windows of the same source. Js provides an interface to monitor the changes of localStorage. With localStorage as the pipeline, communication between labels can be realized.

1) usage:

The sender:

localStorage.setItem('a'.'111')
Copy the code

Receiver:

window.onstorage = (e) = > {console.log(e)} 
// Or so
window.addEventListener('storage'.(e) = > console.log(e))
Copy the code

2) Compatibility:

3) advantages:

Good compatibility.

4) disadvantages:

Indirectly obtain information through data changes, not direct enough, more troublesome to use.

Share Session

Requirements:

Multiple tabs share login credentials. Close all tabs and clear login credentials.

sessionStorage

The browser’s own sessionStorage can clear credentials when closing the window, but it cannot share multiple tabs.

SharedSession

Based on sessionStorage and localStorage mentioned above to achieve multi-label communication, the author has implemented the shared session mechanism between multiple labels.

Usage:

npm i shared-session
#or
yarn add shared-session
Copy the code
import SharedSession from 'shared-session'

// Listen for data changes
SharedSession.listen((data) = > {
    console.log(data)
})

// Get data
SharedSession.getItem('key').then((value) = > {
    console.log(value)
})

// Update data
SharedSession.setItem('key'.'value')

// Delete a field
SharedSession.removeItem('key')

// Clear all data
SharedSession.clear()

Copy the code

The sampleSpade5. Making. IO/multi – tabs -…

warehouseGithub.com/spade5/mult…