5

PushManager.getSubscription()有什麼區別`pushManager.subscribe`和`pushManager.getSubscription`服務工人

Retrieves an existing push subscription. It returns a Promise that resolves to a PushSubscription object containing details of an existing subscription. If no existing subscription exists, this resolves to a null value.

[...]

PushManager.subscribe()

Subscribes to a push service. It returns a Promise that resolves to a PushSubscription object containing details of a push subscription. A new push subscription is created if the current service worker does not have an existing subscription.

根據MDN的pushManager文檔。這裏的方法幾乎相同,只是在getSubcription()的情況下它可以用空值解決。

我基本上明白,我可以簡單地使用subscribe(),Service Worker會在可用的情況下嘗試獲取訂閱,並在不可用的情況下創建新的訂閱。

=>但我正在嘗試做別的事情。我想先嚐試訂閱,如果它解決了null我會嘗試訂閱它。

navigator.serviceWorker.register('./worker.js') 
    .then(function(reg) { 

     // Subscribe push manager 
     reg.pushManager.getSubscription() 
     .then(function(subscription) { 

      if(subscription){ 
       // TODO... get the enpoint here 
      } else { 
       reg.pushManager.subscribe() 
       .then(function(sub){ 
        // TODO... get the endpoint here 
       }); 
      } 

     }, function(error) { 
      console.error(error); 
     }) 
    }); 

但後來我結束了與錯誤:

Uncaught (in promise) DOMException: Subscription failed - no active Service Worker

這是混亂的,並且我懷疑這是Chrome瀏覽器對服務人員的推式API的限制或能可能的錯誤。有沒有人有關於這種奇怪行爲的信息?

回答

相關問題