4

I would like to show GCM service worker message only when there is no open chrome tab in my website or the tab is open and not selected (active).

Here is my code.

Error: chrome is not defined(…).

manifest.json

 {  
  "name": "Webplus Express",  
  "short_name": "Webplus Express",  
  "icons": [{  
    "src": "https://raw.githubusercontent.com/deanhume/typography/gh-pages/icons/typography.png",  
    "sizes": "192x192",
    "type": "image/png" 
    }],  
    "start_url": "/index.html",  
    "display": "standalone",  
    "gcm_sender_id": "298340340811",
    "gcm_user_visible_only": true,
    "background": {
    "scripts": ["service-worker.js"]
    },    
    "permissions": [
    "gcm","tabs","activeTab"
    ]  
  }

service-worker.js

    // The service worker running in background to receive the incoming
// push notifications and user clicks
self.addEventListener('push', function(event) {  
  // Since there is no payload data with the first version  
  // of push messages, we'll grab some data from  
  // an API and use it to populate a notification
  var s_id=0;  
  self.registration.pushManager.getSubscription().then(function(subscription) {

   if(subscription!=null){

   s_id= subscription.endpoint.split("/").slice(-1);

   var mURL="https://www.webplusexpress.com";
   var ok=true;


   chrome.tabs.getAllInWindow(undefined, function(tabs) {
    for (var i = 0;i<tabs.length; i++) {
      if (tabs[i].url && (tabs[i].url.indexOf(mURL)!=-1)) {
        //chrome.tabs.update(tab.id, {selected: true});
        if(tabs[i].highlighted){
          ok=false; 
        }  
        return;
      }
    }

  });

   if (ok){
   event.waitUntil(fetch('https://www.wpe.com/pushnotifyapi?s_id='+s_id).then(function(response) {  

      if (response.status !== 200) {  
        // Either show a message to the user explaining the error  
        // or enter a generic message and handle the
        // onnotificationclick event to direct the user to a web page  
        console.log('Looks like there was a problem. Status Code: ' + response.status);  
        throw new Error();  
      }

      // Examine the text in the response  
      return response.json().then(function(data) {  
        if (data.error || !data.notification) {  
          console.error('The API returned an error.', data.error);  
          throw new Error();  
        }  

        var title = data.notification.title;  
        var message = data.notification.message;  
        var icon = data.notification.icon;  
        console.log('icon received'+icon);
        var notificationTag = data.notification.tag;         

        return self.registration.showNotification(title, {  
          body: message,  
          icon: icon,  
          tag: notificationTag  
        });  
      });  
    }).catch(function(err) {


      console.error('Unable to retrieve data', err);

      var title = 'An error occurred';
      var message = 'We were unable to get the information for this push message';  
      var icon = 'https://www.webplusexpress.com/images/3web+carre.png';  
      var notificationTag = 'notification-error';  
      return self.registration.showNotification(title, {  
          body: message,  
          icon: icon,  
          tag: notificationTag  
        });  
    }) 

  ); 
  }

  }
});

});


self.addEventListener('notificationclick', function(event) {  
  console.log('On notification click: ', event.notification.tag);  
  // Android doesn't close the notification when you click on it  
  // See: http://crbug.com/463146  
  event.notification.close();

  // This looks to see if the current is already open and  
  // focuses if it is  
  event.waitUntil(
    clients.matchAll({  
      type: "window"  
    })
    .then(function(clientList) {  
      for (var i = 0; i < clientList.length; i++) {  
        var client = clientList[i];  
        if (client.url == '/' && 'focus' in client)  
          return client.focus();  
      }  
      if (clients.openWindow) {
        return clients.openWindow('/');  
      }
    })
  );
});
abielita
  • 13,147
  • 2
  • 17
  • 59
Gaddour Mohamed
  • 119
  • 2
  • 9

1 Answers1

0

Referring to Implementing Push Messaging for Chrome might help. It shows each step you need to complete in order to support push messaging in your web app wherein checking if service workers are supported is done before registering the service-worker.js file.

In addition to that, using Page Visibility API to detect when a webpage is visible or in focus might also help. When the user minimizes the webpage or moves to another tab, the API sends a visibilitychange event regarding the visibility of the page as done in SO post - Is there a way to detect if a browser window is not currently active?

Community
  • 1
  • 1
Teyam
  • 7,686
  • 3
  • 15
  • 22
  • 1
    The page visibility API doesn't seem to be available in the service worker scope, so this doesn't help :( – Romain G Jul 24 '17 at 19:23