3

In my React App, I want to implement push notification.

What I've done so far. In the service worker registration step, I added some codes to initialize push manager that handles user subscription, now my app will prompt user to subscribe to push notification.

After subscription, from what I read, the final step is to register event listeners that catches pushes and listen to push notification click. Something like : self.addEventListener('push', function() { // Some codes here })

Now, where should I put the listener codes ? As CRA auto-generated the service-worker for production build

Matt Downey
  • 363
  • 6
  • 18

3 Answers3

0

This doco suggests adding it after fetch in the registerServiceWorker.js.

markau
  • 854
  • 8
  • 21
0

The following solution works only CRA 1.x.x!

As I understood CRA doesn't support extending its service-worker.js from the box.

I've found the following workaround.

1) Install the cra-append-sw

npm install cra-append-sw --save

2) Add an extension file custom-sw.js to the root directory

self.addEventListener("push", event => {
    const data = event.data.json()
    const { title } = data
    const body = {
        body: data.body,
        icon: data.icon
    }
    event.waitUntil(self.registration.showNotification(title, body))
})

3) Patch the package.json to run the cra-append-sw during debugging and building

"scripts": {
    ...
    "start": "npm-run-all -p watch-css start-js && cra-append-sw --mode dev ./custom-sw.js",
    ...
    "build": "npm-run-all build-css build-js && cra-append-sw ./custom-sw.js",
}
Vladimir Vlasov
  • 1,860
  • 3
  • 25
  • 38
0

For anyone looking for this, here is a good guide on how to achieve push notifications in React.

Guide: Integrating Push Notifications in your Node/React Web App

Caio Mar
  • 2,344
  • 5
  • 31
  • 37