3

我有一個註冊的服務人員,但我想循環一個函數來檢查服務器上的更新,並顯示通知,即使關閉標籤。Javascript服務人員onload顯示通知

使用serviceworker.js中的以下代碼,我得到一個錯誤; 「未被捕獲(承諾)TypeError:ServiceWorkerRegistration上沒有可用的註冊。」

self.registration.showNotification(title, { 
     body: 'We have received a push message', 
     icon: '', 
     tag: '' 
}) 

我希望當瀏覽器打開時像Facebook一樣打開通知。

+0

你在哪裏運行該代碼的生命週期?它是否在服務工作者中註冊的事件監聽器之一中? – Marco

+0

@Marco沒有它沒有。我首先把它放在那裏,但是我不知道如何調用這些事件來自動運行。 – Relm

+1

不幸的是,你不能這麼做,我建議你看一下Service Worker Cookbook上的例子:https://serviceworke.rs/,這將有助於澄清你的想法。 – Marco

回答

0

那麼,你首先需要了解的service-worker

// listen for a push notification from gcm, as only it can reiterate 
    // your push-notifications to your clients subscriber id 
    // put your code inside listener 

     self.addEventListener('push', function(event) { 
      console.log('Received a push message', event); 

     // here you can make rest calls to fetch data against the subscriber-id 
     // and accordingly, set data 
     // keep in mind that your server sends push notifications to gcm 
     // and then your subscribers receive them here 

     var title = 'title' || 'data-from-rest-call'; 
     var body = 'body' || 'data-from-rest-call'; 
     var icon = '/your image path' || 'data-from-rest-call'; 
     var tag = 'tag' || 'data-from-rest-call'; 

     // waitUntil is a callback, it triggers when the push is ready. 
     event.waitUntil( 
     //here your ready notifications get triggered 
     self.registration.showNotification(title, { 
      body: body, 
      icon: icon, 
      tag: tag 
     }) 
    ); 
    }); 

Refer google's getting started with web-push-notifications for detailed understanding.