Andreas Baran
Andreas Baran

Reputation: 659

ServiceWorkerRegistration.showNotification in PWA, bring app to foreground

I'm showing notification in my PWA. It works and it shows the notification. But i cant seem to find out how to bring the app to foreground if you click the notification (if possible)?

Usecase:

A notification is showned to the user while he is on facebook. Then when the user clicks the notification, then i would like my app to go to foreground.

Is this possible when im not working natively?

Here is my test code:

 navigator.serviceWorker.register('service-worker.js');
  Notification.requestPermission(function(result) {
    if (result === 'granted') {
      navigator.serviceWorker.ready.then(function(registration) {
        registration.showNotification('Notification with ServiceWorker');
      });
    }
  });

Upvotes: 1

Views: 7923

Answers (2)

Andreas Baran
Andreas Baran

Reputation: 659

So my problem was my lack of knowledge! I had not figured out that the onclick handler should be placed in the service-worker.

I found good help here:

https://developers.google.com/web/fundamentals/push-notifications

https://web-push-book.gauntface.com/demos/notification-examples/

Upvotes: 1

Chris Love
Chris Love

Reputation: 3893

You can open a URL within your PWA. It will open it in a new tab in the browser, even if there is a tab already open to your PWA.

    handleResponse( event ) {

    console.log( '[Service Worker] Notification click Received. ${event}' );

    if ( event.action && validURL( event.action ) ) {

        clients.openWindow( event.action );

    }

    event.notification.close();

}

Upvotes: 0

Related Questions