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. js获取url参数,操作url参数

    function getParam(key) { var tmp = location.search; tmp = decodeURIComponent(tmp); var index = tmp.i ...

  2. Codevs 2080 特殊的质数肋骨

      题目描述 Description 农民约翰的母牛总是产生最好的肋骨. 你能通过农民约翰和美国农业部标记在每根肋骨上的数字认出它们. 农民约翰确定他卖给买方的是真正的质数肋骨,是因为从右边开始切下肋 ...

  3. codevs 1269 匈牙利游戏——次短路(spfa)

    欢迎来到匈牙利游戏!布达佩斯(匈牙利首都)的街道形成了一个弯曲的单向网络. 你被强制要求参加一个赛跑作为一个TV秀的一部分节目,比赛中你需要穿越这些街道,从s开始,到t结束. 很自然的,你想要尽快的完 ...

  4. Android的CheckBox(多选框)

    1.布局文件 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:t ...

  5. 7.0不通过FileProvider解决调用相机给uri问题异常

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//严格模式 StrictMode.VmPolicy.Builder builder = ...

  6. hdu 5150(水题)

    Sum Sum Sum Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total ...

  7. hdu 1162(最小生成树)

    Eddy's picture Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)To ...

  8. POJ 3225.Help with Intervals-线段树(成段替换、区间异或、简单hash)

    POJ3225.Help with Intervals 这个题就是对区间的各种操作,感觉这道题写的一点意思都没有,写到后面都不想写了,而且更神奇的是,自己的编译器连结果都输不出来,但是交上就过了,也是 ...

  9. POJ 3620 Avoid The Lakes【DFS找联通块】

    Avoid The Lakes Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 6826   Accepted: 3637 D ...

  10. #417 Div2 E (树上阶梯博弈)

    #417 Div2 E 题意 给出一颗苹果树,设定所有叶子节点的深度全是奇数或偶数,并且包括根在内的所有节点上都有若干个苹果. 两人进行游戏,每回合每个人可以做下列两种操作中的一种: 每个人可以吃掉某 ...