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

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

  1. [PWA] Enable Push Notification in your web app

    1. Clone the project: git clone https://github.com/GoogleChrome/push-notifications.git 2. install th ...

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

  3. [Erlang 0106] Erlang实现Apple Push Notifications消息推送

        我们的IOS移动应用要实现消息推送,告诉用户有多少条消息未读,类似下图的效果(笑果),特把APNS和Erlang相关解决方案笔记于此备忘.          上面图片中是Apple Notif ...

  4. iOS 中的Push Notifications简单实现(APNS)

    Android中的通知只有一种,就是Local Notifications,而iOS中除了Local Notifications外,还有一种Push Notifications.ios的这2种noti ...

  5. Apple Remote Push Notifications

    1.帮助文档参考: https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/Remote ...

  6. (转)pem, cer, p12 and the pains of iOS Push Notifications encryption

    转自:http://cloudfields.net/blog/ios-push-notifications-encryption/ The serious pains of setting up a ...

  7. Xcode - Your development team, "", does not support the Push Notifications capability.

    1.问题描述: 从git上checkout了别人的一个工程文件,选择team时,Xcode显示如下问题 Your development team, "xxx.xxx.xxx", ...

  8. iOS8 Push Notifications

    本文转载至 http://blog.csdn.net/pjk1129/article/details/39551887   原贴地址:https://parse.com/tutorials/ios-p ...

  9. Your development team, "", does not support the Push Notifications capability.

    问题: Your development team, "", does not support the Push Notifications capability. 解决方法: 1 ...

随机推荐

  1. 从K近邻算法、距离度量谈到KD树、SIFT+BBF算法

    转载自:http://blog.csdn.net/v_july_v/article/details/8203674/ 从K近邻算法.距离度量谈到KD树.SIFT+BBF算法 前言 前两日,在微博上说: ...

  2. DiskGenius

    DiskGenius是一款集磁盘分区管理与数据恢复功能于一身的工具软件.它即是一款功能强大.灵活易用的分区软件,同时也是一款技术高超.功能全面的数据恢复软件.它不仅具备与分区管理有关的几乎全部功能,支 ...

  3. linux启动流程梳理【转】

    接触linux系统运维已经好几年了,常常被问到linux系统启动流程问题,刚好今天有空来梳理下这个过程:一般来说,所有的操作系统的启动流程基本就是: 总的来说,linux系统启动流程可以简单总结为以下 ...

  4. Generator函数的语法

    简介 Generator函数是ES6关于异步编程的解决方案.Generator函数能够让函数暂停执行(即交出函数的执行权),简单直白点来理解,Generator函数就是一个状态机,内部封装了多个状态( ...

  5. xCode中去除“Implicit declaration of function 'sysctl' is invalid in C99” 警告

    http://blog.csdn.net/dreambegin/article/details/8609121 一般出现该问题是因为通过C调用了unix/linux 底层接口,所以需要调整c语言的编译 ...

  6. SpringBoot部署到Linux服务器

    今天来谈一下,用SpringBoot写的Demo来配置到Linux服务器. 这里,我用阿里云服务器作为实例,SpringBoot集成了SpringMvC+ mybatis 框架,用maven管理jar ...

  7. linux文件系统之loop环设备--新建一个文件系统并挂载

    1.  /dev目录下有所有已经连接到操作系统上的设备,他们能在/dev里出现就表示他们在硬件层面和系统核心层面被识别了.对于stdin.stdout.zero等设备是可以直接用> <这些 ...

  8. java1.7集合源码阅读:ArrayList

    ArrayList是jdk1.2开始新增的List实现,首先看看类定义: public class ArrayList<E> extends AbstractList<E> i ...

  9. 读取EXCEL的办法

    private void button9_Click(object sender, EventArgs e) { var folder =new FolderBrowserDialog(); if ( ...

  10. 关于yii2 的db log 日志 错误处理errorHandler

    log 通过配置Web.config来完成 1 数据库增加 ‘前缀_log’表 2 配置Web.config 'bootstrap' => ['log'], 'components' => ...