[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!‘
    })
  }

原文地址:https://www.cnblogs.com/Answer1215/p/10206777.html

时间: 2024-08-10 21:30:41

[PWA] Add Push Notifications to a PWA with React in Chrome and on Android的相关文章

Send Push Notifications to iOS Devices using Xcode 8 and Swift 3, APNs Auth Key

Send Push Notifications to iOS Devices using Xcode 8 and Swift 3 OCT 6, 2016 Push notifications are a great way to ensure your users re-engage with your app every once in a while, but implementing them on iOS can be challenging, especially with all o

使用Google Cloud Messaging (GCM),PHP 开发Android Push Notifications (安卓推送通知)

什么是GCM? Google Cloud  Messaging (GCM) 是Google提供的一个服务,用来从服务端向安卓设备发送推送通知. GCM分为客户端和服务端开发. 这里我们只介绍服务端开发.其实过程非常简单,只需利用PHP发送POST数据. api key的取得? 待补充? class GCM { public $api_key = "AIzaSyAU3wZs9raik-mHQ"; function __construct() { } /** * Sending Push

iOS10 App适配权限 Push Notifications 字体Frame 遇到的坑!!!!

添加配置权限 <!-- 相册 --> <key>NSPhotoLibraryUsageDescription</key> <string>"xx"想使用您的相册,需要您的允许</string> <!-- 相机 --> <key>NSCameraUsageDescription</key> <string>"xx"想使用您的相机,需要您的允许</strin

iOS8 Push Notifications

本文转载至 http://blog.csdn.net/pjk1129/article/details/39551887 原贴地址:https://parse.com/tutorials/ios-push-notifications github地址:https://github.com/ParsePlatform/PushTutorial iOS Push通知已经广泛应用于实际开发中,iOS8与之前注册push有所不同,这里把如何潜入代码贴一下,以作记录,详情请看上面地址链接 Adding Co

[PWA] Add web app to your Home Screen

Clone: Link Modify the structure: Move css, js, image, index.html to an 'app' folder. manifest.json: { "name": "Fireworks App", "short_name": "Fireworks", "icons": [ { "src":"images/firework

[PWA] Access the Camera in a PWA built with React

It's possible to access some, but not all, of the native device features from a PWA. One that we canaccess, is the camera and camera roll. We'll use two different methods to allow users to upload images to our application. First, we'll add a file inp

iOS中远程推送实现—在Apple的生产环境上测试Push Notifications功能

1.在“Provisioning Profiles”中点击“Add”按钮. 2.在“What type of provisioning profile do you need?”页面中选择“Distribution”下的“Ad Hoc”,点击“Continue”按钮,如下图 3.在“Select App ID.”页面,选择“App ID”,点击“Continue”按钮. 4.在“Select certificates.”页面中,选中证书,点击“Continue”按钮. 5.在“Select de

Android Push Notifications using Google Cloud Messaging (GCM), PHP and MySQL

http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/ 按照文章的链接的步骤,实现GCM-HTTP在client 和app server之间的部署.链接一下供须要的同学參考. 在从本地Server移植到web server遇到的问题: 1.Google Api Key是绑定serverIP的,所以在本地换到Web的时候,Google

Progressive Web App

下一代 Web 应用? 近年来,Web 应用在整个软件与互联网行业承载的责任越来越重,软件复杂度和维护成本越来越高,Web 技术,尤其是 Web 客户端技术,迎来了爆发式的发展. 包括但不限于基于 Node.js 的前端工程化方案:诸如 Webpack.Rollup 这样的打包工具:Babel.PostCSS 这样的转译工具:TypeScript.Elm 这样转译至 JavaScript 的编程语言:React.Angular.Vue 这样面向现代 Web 应用需求的前端框架及其生态,也涌现出了