Search code examples
google-chromenotificationsservice-workerweb-pushpush-api

ServiceWorker Chrome Push Notifications - Forward to new page


What I'm trying to do is see if a tab to my website is open in Chrome, and if so focus on it AND forward them to a new URL that I'm passing through.

For reference, when you see "event.notification.data" it will be a link such as "https://www.example.com/mobile/profile.php?id=Webmaster"

I can focus on the tab, but then I cannot make that tab redirect to the URL I have stored in "event.notification.data"

Here is my code

self.addEventListener('notificationclick', function(event) {
  event.notification.close();
  event.waitUntil(
    clients.matchAll({  
      type: "window" 
    })
    .then(function(clientList) {  
      // loop through all the tabs
      for (var i = 0; i < clientList.length; i++) {  
        var client = clientList[i]; 
        //check if a tab starts with the websites name 
        if (client.url.indexOf("https://www.example.com/mobile") == 0 && 'focus' in client){
          //a tab matched! Check if the data (a link) is there

          //------
          //THIS IS WHERE I NEED HELP
          //------
          if(event.notification.data != ''){
            //yes! event.notification.data is a link, focus on the tab and forward them there
            client.focus();
            client.navigate(event.notification.data);
          } else {
            //no! event.notification.data was blank, focus on the tab and forward them to the general site
            client.focus();
            client.navigate('https://www.example.com/mobile');
          } 

        }
      }  
      if (clients.openWindow) {
        if(event.notification.data != ''){
          clients.openWindow(event.notification.data);
        } else {
          clients.openWindow('https://www.heftynet.com/mobile');
        }  
      }
    })
  );
});

Solution

  • It looks like client.navigate() is not implemented yet (as of September 10, 2015), not even in Chrome Canary. It was specified only a few months ago, in June 2015. Here is the feature status page, and the relevant Chromium ticket. Your code will probably work once navigate() is implemented.