0

I need to show a SW notification when window cilent is hidden and should not show a notification when window client visibility state is visible.

I have tried below code. But SW shows default notification.

This site has been updated in the background

Could anyone please help me out.

    self.addEventListener('push', function(event) {
    if (event.data) {
           console.log('This push event has data: ',event.data.text());
    } else {
           console.log('This push event has no data.');
    }

 // isClientFocused will return true if any of the window client is visible.

  const promiseChain = isClientFocused()
  .then(function(clientIsVisible){
    if (clientIsVisible) {
           return self.registration.showNotification('Dummy') 
     .then(function(){ 

      self.registration.getNotifications().then(function(notifications)
      {
         notifications.forEach(function(notification){
                notification.close();
            })
          })
      });
    }

//Client is not focused.So need to show notification.

    else{
        const title = 'POC Demo';
        const options = {
        body: event.data.text(),
        tag: 'data-notification',
        data: {
            message: event.data.text()
          }
       };

        return self.registration.showNotification(title,options); 
       }  
  });

  event.waitUntil(promiseChain);

 });
Mathi kumar
  • 373
  • 1
  • 4
  • 10
  • 1
    See also https://developers.google.com/web/fundamentals/engage-and-retain/push-notifications/subscribing-a-user and what they write about userVisibleOnly setting – Stef Chäser Jul 26 '17 at 10:54
  • @Marco Thanks for the prompt reply. My question is little bit different. If I did not resolve the showNotification promise in push event , I will get notified by browser "This site has been updated in the background". But today I am not facing this issue. Is there any change? do you have any ideas? – Mathi kumar Jul 26 '17 at 12:40
  • 1
    Hey @Mathikumar, the question is basically the same as the other one. Browsers won't always allow push messages if you don't show any notification, there are limitations (see my reply from the other question). – Marco Castelluccio Jul 27 '17 at 14:28

0 Answers0