1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| (function () {
const register = (config) => { if ("serviceWorker" in navigator) { let swUrl = `${config.path}/${config.name}?v=${config.ver}`; navigator.serviceWorker .register(swUrl) .then((swReg) => { console.log("Service Worker注册成功"); if (config && config.onRegister) { config.onRegister(swReg); }
swReg.onupdatefound = (e) => { let installingWorker = swReg.installing; if (!installingWorker) { return; } installingWorker.onstatechange = (e) => { if (installingWorker.state === "installed") { if (navigator.serviceWorker.controller) { config.log && console.log("Service Worker已安装更新"); if (config && config.onUpdate) { config.onUpdate(swReg); } } else { config.log && console.log("Service Worker已安装"); if (config && config.onSuccess) { config.onSuccess(swReg); } } } }; }; }) .catch((err) => { if (config && config.onError) { config.onError(err); } console.error("Service Worker注册期间发生错误:", err); });
if (navigator.serviceWorker.controller) { navigator.serviceWorker.controller.postMessage( "这是从window环境postMessage()" );
const channel = new MessageChannel(); channel.port1.onmessage = (e) => { console.log( `${new Date().toLocaleString()}, index.html port1收到消息:${ e.data }` ); }; navigator.serviceWorker.controller.postMessage( "这是index.html向port2 postMessage()", [channel.port2] ); }
navigator.serviceWorker.onmessage = (e) => { console.log( `${new Date().toLocaleString()}, index.html收到的消息: ${ e.data }` ); }; } };
const unregister = () => { if ("serviceWorker" in navigator) { navigator.serviceWorker.ready.then((swReg) => { swReg.unregister((result) => { result && console.log("Service Worker注销成功"); }); }); } };
const broad = new BroadcastChannel("c1"); broad.onmessage = (e) => { console.log( `${new Date().toLocaleString()}, index.html收到的Service Worker广播消息:${ e.data }` ); };
register({ ver: 1, path: "", name: "sw.js", log: true, onRegister: () => {}, onSuccess: () => {}, onUpdate: () => {}, onError: (err) => {}, }); })();
|