zoukankan      html  css  js  c++  java
  • service worker(二)之主页面与service worker通信

    实现一个主页面发送消息,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

  • 相关阅读:
    匿名方法
    C# 正则表达式
    c# 预处理命令
    反射
    特性(attribute)
    c# 交换两个变量
    构造函数
    泛型
    Event事件
    委托
  • 原文地址:https://www.cnblogs.com/raind/p/11113953.html
Copyright © 2011-2022 走看看