service worker(二)之主頁面與service worker通訊

實現一個主頁面發送消息,worker搜到信息向全部的頁面派發消息(當前頁面除外)html

msg.htmlsegmentfault

<!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.jspromise

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.jsapp

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)
})

參考連接:post

http://www.javashuo.com/article/p-bxybtqsv-mq.html
https://www.yaruyi.com/article/service-worker-connectionui

相關文章
相關標籤/搜索