What it does: You can use SharedWorker to transfer information between different Windows within the same source

Building worker scripts

let pool = [];
onconnect = function (e) {
  let port = e.ports[0];
  pool.push(port);
  port.onmessage = function (e) {
    pool.forEach((v) = >{ v ! = port && v.postMessage(e.data); }); }; };Copy the code

Build a data sharing channel

export class SharedDataChannel {
  constructor(url, cb) {
    this.sharedWorker = new SharedWorker(url);
    this.sharedWorker.port.onmessage = (e) = > {
      cb && cb(e.data);
    };
  }

  post(data) {
    this.sharedWorker.port.postMessage(data); }}Copy the code

Initialize on multiple pages

<script type="module">
    import { SharedDataChannel } from "./index.js";
    const channel = new SharedDataChannel("./worker.js".(res) = > {
    document.querySelector("#content").innerHTML += `${res} </br>`;
    });
    document.querySelector("#send").addEventListener("click".() = > {
    channel.post("Data sent from the login page");
    });
</script>

<body>The login page<button id="send">send</button>
    <p id="content"></p>
</body>
Copy the code

debugging

Chrome ://inspect/#workers navigate to chrome://inspect/#workers and find the SharedWorker, then click “inspect”, then you can pull up the SharedWorker console.

The effect