作用: 通过SharedWorker可以在同源内的不同窗口之间传递信息
构建worker脚本
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); }); }; };
构建数据共享通道
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); } }
在多个页面进行初始化
<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("登录页面发送的数据"); }); </script> <body> 登录页面 <button id="send">发送</button> <p id="content"></p> </body>
调试
chrome://inspect/#workers 导航到 chrome://inspect/#workers 并找到共享的 worker,然后单击"inspect",然后你可以拉起 SharedWorker 的控制台。
效果