2016-09-09 80 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

相關問題