zoukankan      html  css  js  c++  java
  • [PWA] Add Push Notifications to a PWA with React in Chrome and on Android

    On Android and in Chrome (but not on iOS), it's possible to send push notifications with a PWA. We'll start by asking the user for permission to send them push notifications, and then look at how to intercept the push event in a service worker. We can test the push notifications directly in Chrome's devtools, and we will also make a button that can trigger a push notification directly from the PWA app code itself.

    Install:

    npm install web-push -g

    Generate the key:

    web-push generate-vapid-keys

    In src/serviceworker.js (Generated by create-react-app) we need to save access to the service worker registration here. Set global.registration = registration.

    function registerValidSW(swUrl, config) {
      navigator.serviceWorker
        .register(swUrl)
        .then(registration => {
    
          global.registration = registration
    
        ...
        })
        .catch(error => {
          console.error('Error during service worker registration:', error);
      });
    }

    Register function for push notification:

      function subscribe () {
        const key = 'xxx-xxx-xxx';
        global.registration.pushManager.subscribe({
          userVisibleOnly: true,
          applicationServerKey: urlB64ToUint8Array(key)
          }).then(sub => {
            console.log("Subscribed!")
          }).catch(err => {
            console.log("Did not subscribe.")
          })
      }
    
    function urlB64ToUint8Array(base64String) {
      const padding = '='.repeat((4 - base64String.length % 4) % 4);
      const base64 = (base64String + padding)
        .replace(/-/g, '+')
        .replace(/_/g, '/');
    
      const rawData = window.atob(base64);
      const outputArray = new Uint8Array(rawData.length);
    
      for (let i = 0; i < rawData.length; ++i) {
        outputArray[i] = rawData.charCodeAt(i);
      }
      return outputArray;
    }

    Now in src/sw.js: we can listen for a 'push', event from the push server just like we did for fetch. Add a push eventListener. We're going to tell the event to waitUntil we show a push notification. Access the server worker registration with self.registration and call showNotification. That takes the title as the first argument and a hash of options as the second. For now, we'll set the iconto an icon that we already have in the public folder and the body to whatever text comes through the push from the server.

    self.addEventListener('push', event => {
      event.waitUntil(self.registration.showNotification('Todo List', {
        icon: '/icon-120.jpg',
        body: event.data.text()
      }))
    })

    Last, in App.js, we write code to send push message:

      testPushMessage = () => {
        global.registration.showNotification('Test Message', {
          body: 'Success!'
        })
      }
  • 相关阅读:
    物联网需要自己的专有操作系统
    基于visual Studio2013解决C语言竞赛题之0201温度转换
    基于visual Studio2013解决C语言竞赛题之前言
    物联网操作系统再思考:建设更加主动的网络,面向连接一切的时代
    经典排序算法分析和代码-下篇
    Windows XP硬盘安装Ubuntu 12.04双系统图文详解
    Eclipse 编码区-保护色-快捷大全
    Android最新源码4.3下载-教程 2013-11
    Windows XP硬盘安装Ubuntu 12.04双系统图文详解
    惠威的M200MK3的前级电子分频板
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10206777.html
Copyright © 2011-2022 走看看