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. Codeforces Round #281 (Div. 2) B 模拟

    B. Vasya and Wrestling time limit per test 2 seconds memory limit per test 256 megabytes input stand ...

  2. 怎么用tomcat对socket接口的程序进行调试

    对socket(套接字)的demo方法大多都是用main方法进行测试的,那如何用tomcat进行测试呢? 这里需要借助一个工具:工具的名字是:Sockettool.exe .下图是该工具的内容.连上监 ...

  3. spring in action 学习十一:property placeholder Xml方式实现避免注入外部属性硬代码化

    这里用到了placeholder特有的一个语言或者将表达形式:${},spring in action 描述如下: In spring wiring ,placeholder values are p ...

  4. Netapp exportfs NFS Config CLI Guide

    Netapp exportfs NFS Config CLI Guide A quick and simple Netapp NFS configuration guide with commands ...

  5. jquery,zepto插件编写相关

    1. $.fn.pluginName = function(opt){}就是为jquery的prototype定义了函数, 这样, 任何一个jquery对象都可以使用这个成员函数, 这种写法直观明了, ...

  6. POJ3668 Game of Lines

     Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 6791   Accepted: 2523 Description Farm ...

  7. [ CodeVS冲杯之路 ] P1068

    不充钱,你怎么AC? 题目:http://codevs.cn/problem/1068/ 这是一道神DP题,一开始状态设计错了,用位置和剩余卡片做下标,过了样例数据WA了 好了,讲正解,设 f[i][ ...

  8. 培训补坑(day3:网络流&最小割)

    继续补坑.. 第三天主要是网络流 首先我们先了解一下网络流的最基本的算法:dinic 这个算法的主要做法就是这样的: 在建好的网络流的图上从源点开始向汇点跑一遍BFS,然后如果一条边的流量不为0,那么 ...

  9. Vplayer服务配置-手机播放局域网视频

    如何使用 UPnP DLNA Cedric Fung 2012-08-03 如何使用 UPnP DLNA · Cedric Fung · 2012-08-03 UPnP / DLNA 通用即插即用 ( ...

  10. Bash 文件夹操作

    mkdir, rm,find都是对tree结构的文件夹进行的操作,可以安装tree用tree命令直接打印出树的结构 文件夹的操作分为只操作当前文件夹的集合数据和迭代操作的tree数据 Bash迭代当前 ...