[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 icon
to 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!' }) }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2018-01-02 [Poi] Use Poi to Build an Index.js with Modern JavaScript Features
2016-01-02 [ES6] Rest Parameter
2016-01-02 [ES6] Function Params
2015-01-02 [MEAN Stack] First API -- 7. Using Route Files to Structure Server Side API
2015-01-02 [MEAN Stack] First API -- 6. Using Express route instance
2015-01-02 [ES6] 19. for ... of
2015-01-02 [ES6] 18. Map