2016-09-09 41 views
2

我是Google Chrome推送通知的新手,我刚刚在这里阅读了一些问题和解答,在stackoverflow上我已经以这个简单的推送通知javascript结束了。Chrome推送通知 - 点击后如何打开URL地址?

navigator.serviceWorker.register('sw.js'); 

function notify() { 

    Notification.requestPermission(function(result) { 

     if (result === 'granted') { 
      navigator.serviceWorker.ready.then(function(registration) { 

       registration.showNotification('test notification', { 
        body: 'Hey I am test!', 
        icon: 'image.png', 
       }); 

      }); 
     } 
    }); 

} 

它只是简单的通知,但我需要打开一个新的窗口与其他网页后点击通知。

我知道这是可能的,但我找不到使用“serviceWorker”语法的示例。

请帮忙。谢谢。

回答

5

我猜你是在Service Worker上下文中,因为这是接收推送通知的地方。所以你有self对象来添加一个事件监听器,这会对通知的点击作出反应。

self.addEventListener('notificationclick', function(event) { 
    let url = 'https://example.com/some-path/'; 
    event.notification.close(); // Android needs explicit close. 
    event.waitUntil(
     clients.matchAll({type: 'window'}).then(windowClients => { 
      // Check if there is already a window/tab open with the target URL 
      for (var i = 0; i < windowClients.length; i++) { 
       var client = windowClients[i]; 
       // If so, just focus it. 
       if (client.url === url && 'focus' in client) { 
        return client.focus(); 
       } 
      } 
      // If not, then open the target URL in a new window/tab. 
      if (clients.openWindow) { 
       return clients.openWindow(url); 
      } 
     }) 
    ); 
}); 
+0

是的,就是这样,谢谢! – shitwithcode

+0

如果有帮助,请接受答案,因此它不会在问题列表中保留为“未答复”。 – C14L

+0

我需要这个修改,clients.matchAll({includeUncontrolled:true,type:'window'}),让它工作。 – 0x4f3759df