registration.showNotification is not a function

Viewed 11467

I'm using serviceworker-webpack-plugin to create a service worker in my reactjs apps.

I've followed the example to register the service worker in the main thread. I've learnt that Html5 Notification doesn't work on Android chrome, so I used registration.showNotification('Title', { body: 'Body.'}); instead of new Notification('...') to push notifications. But when I tested it on the desktop chrome, it throws this error

registration.showNotification is not a function

Is the registration.showNotification only available on Android chrome but not on the desktop?

public componentDidMount(){

    if ('serviceWorker' in navigator &&
        (window.location.protocol === 'https:' || window.location.hostname === 'localhost')
    ) {
        const registration = runtime.register();

        registerEvents(registration, {
            onInstalled: () => {

                registration.showNotification('Title', { body: 'Body.'});
            }
        })
    } else {
        console.log('serviceWorker not available')
    }
}
2 Answers

Below solution worked for me. Can try.

The main root cause of .showNotification() not firing is service worker. Service worker is not getting registered. So it wont call registration.showNotification() method.

  • Add service-worker.js file to your project root directory

  • You can download service-worker.js file from Link

Use below code to register service worker and fire registration.showNotification() method.

const messaging = firebase.messaging();
messaging.onMessage(function (payload) {
  console.log("Message received. ", payload);
            NotisElem.innerHTML = NotisElem.innerHTML + JSON.stringify(payload);
            //foreground notifications

            if ('serviceWorker' in navigator) {

                navigator.serviceWorker
                    .register('./service-worker.js', { scope: './' })
                    .then(function (registration) {
                        console.log("Service Worker Registered");
                        setTimeout(() => {
                            registration.showNotification(payload.data.title, {
                                body: payload.data.body,
                                data: payload.data.link
                            });
                            registration.update();
                        }, 100);
                    })
                    .catch(function (err) {
                        console.log("Service Worker Failed to Register", err);
                    })

     }
 });
Related