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. POJ3680:Intervals(离散化+最大流最小费用)

    Intervals Time Limit: 5000MS   Memory Limit: 65536K Total Submissions: 9320   Accepted: 4014 题目链接:ht ...

  2. Three Garlands~Educational Codeforces Round 35

    C. Three Garlands time limit per test 2 seconds memory limit per test 256 megabytes input standard i ...

  3. 制作servlet模板

    制作servlet模板 选中window-->preference--->搜索template--->选中java下面的template new一个 Name的设置,当你在eclip ...

  4. What makes grep consider a file to be binary?

    grep -a worked for me: $ grep --help [...] -a, --text equivalent to --binary-files=text

  5. 20170416郑州市轻工业学院ACM校赛

    这是个星期天,但是,这种非一线城市,重点城市什么的高中,放假从来不按套路出牌,几乎可以说能给你一天是福气.当然,比县里好的多,问在县里上高中的初中同学,放假更是比我们一天里的午休+晚上吃饭时间还要少. ...

  6. 【bzoj1951】【古代猪文】Lucas定理+欧拉定理+孙子定理

    (上不了p站我要死了,当然是游戏原画啊) Description (题面倒是很有趣,就是太长了) 题意: 一个朝代流传的猪文文字恰好为N的k分之一,其中k是N的一个正约数(可以是1和N).不过具体是哪 ...

  7. [POI2014]Solar Panels

    题目大意: $T(T\le1000)$组询问,每次给出$A,B,C,D(A,B,C,D\le10^9)$,求满足$A\le x\le B,C\le y\le D$的最大的$\gcd(x,y)$. 思路 ...

  8. xml文件生成与下载

    写在前面: 最近要做一个新的功能,点击按钮,可以根据数据生成对应的xml文件并保存.下面记录一下在做的过程的一些疑惑与问题(我就是太笨了,一些很简单的知识都不知道,不过通过这次跟蛋蛋的交流,解决了我的 ...

  9. unity3d Billboard

    CameraFacingBillboard   CameraFacingBillboard From Unify Community Wiki   Jump to: navigation, searc ...

  10. 我学MSMQ(一)

    一.通过这篇文章主要是对自己学习MSMQ进行小结,并希望能把自己的想法写出来,能和一些也正在研究MSMQ的朋友共同学习,并希望能给予指导和建议         二.首先是MSMQ的一些理论上的知识   ...