<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="./main.css"> </head> <body> <div class="container">service worker</div> <script src="./app.js"></script> </body> </html>
main.csscss
.container{ color: red; }
app.jshtml
// 註冊 serviceWorker if (navigator.serviceWorker) { navigator.serviceWorker.register('./service-worker.js', { scope: './' // 做用域 }).then(function (reg) { console.log(reg); }).catch(function (e) { console.log(e); }) } else { alert('Service Worker is not supported') }
service-worker.js前端
// 監聽 serviceWorker install 事件 self.addEventListener('install', function(e) { // 會接受一個 promise 對象,返回成功後纔會進行後續的運行 e.waitUntil( // caches 就是開啓一個 cacheStorage caches.open('app-v1').then(function(cache){ console.log('open cache'); return cache.addAll([ './app.js', './main.css', './serviceWorker.html' ]) }) ) }) self.addEventListener('fetch', function(event) { // 讀緩存 event.respondWith( caches.match(event.request).then(function(res) { if (res) { return res; } else { // 經過 fetch 方法向網絡發起請求 fetch(url).then(function() { if (res) { // 對於新請求到資源存儲到咱們的 cachestorage中 } else { // 用戶提示 } }) } }) ) })
<!DOCTYPE html> <html lang="en"> <head> </head> <body> <ul id="msg-box"></ul> <input type="text" id="msg-input" /> <button id="send-msg-button">發送</button> <script src="./msgapp.js"></script> </body> </html>
msgapp.jsweb
// 註冊 serviceWorker if (navigator.serviceWorker) { var sendBtn = document.getElementById('send-msg-button'); var msgInput = document.getElementById('msg-input'); var msgBox = document.getElementById('msg-box'); sendBtn.addEventListener('click', function(){ // 點擊btn ,主頁往 servicework 發事件 navigator.serviceWorker.controller.postMessage(msgInput.value); }) navigator.serviceWorker.addEventListener('message', function(event){ msgBox.innerHTML = msgBox.innerHTML + ('<li>' + event.data.message + '</li>') }) navigator.serviceWorker.register('./msgsw.js', { scope: './' // 做用域 }).then(function (reg) { console.log(reg); }).catch(function (e) { console.log(e); }) } else { alert('Service Worker is not supported') }
msgsw.js編程
// 監聽 serviceworker message 事件 self.addEventListener('message', function(event) { var promise = self.clients.matchAll().then(function(clientList){ var senderID = event.source ? event.source.id : 'unknown'; clientList.forEach(client => { if(client.id == senderID) { return } else { client.postMessage({ client: senderID, message: event.data }) } }); }) event.waitUntil(promise); })