实现一个主页面发送消息,worker搜到信息向所有的页面派发消息(当前页面除外)
msg.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>主页面与serviceWorker的通信</title>
</head>
<body>
<div>
<ul>
<li>占位符</li>
</ul>
<input id="input" type="text">
<button id="btn">发送信息</button>
</div>
</body>
<script src="./msgApp.js"></script>
</html>
msgApp.js
const input = document.getElementById('input')
const btn = document.getElementById('btn')
btn.onclick = function() {
console.log(input)
navigator.serviceWorker.controller.postMessage(input.value)
}
navigator.serviceWorker.addEventListener('message', function(e) {
const ul = document.getElementsByTagName('ul')[0]
const li = document.createElement('li')
li.innerHTML = e.data.message
ul.appendChild(li)
})
navigator.serviceWorker
.register('./msgAppsw.js', { scope: './' })
.then(req => {
console.log(req)
})
.catch(e => {
console.log(e)
})
msgAppsw.js
self.addEventListener('message', function(e) {
const promise = self.clients.matchAll().then(function(clients) {
let senderId = e.source ? e.source.id : 'unknow'
clients.forEach(client => {
if (senderId === client.id) {
return
} else {
client.postMessage({
client: senderId,
message: e.data
})
}
})
})
e.waitUntil(promise)
})
参考链接:
https://segmentfault.com/a/1190000008050742#articleHeader1
https://www.yaruyi.com/article/service-worker-connection