2016-05-14 38 views
0

上週我一直在使用Service Worker,目前安裝了用於脫機緩存文件和推送通知的優秀安裝。顯示服務工作人員狀態的消息

還有最後一兩件事,我希望能夠以顯示對服務人員的某些狀態的UI消息,目前我對激活狀態下面的代碼:

if ('serviceWorker' in navigator) { 
navigator.serviceWorker.addEventListener('controllerchange',function(event) { 
    navigator.serviceWorker.controller.addEventListener('statechange', function() { 
if (this.state === 'activated') { 
    document.getElementById('offlineNotification').classList.remove('hidden'); 
} 
}); 
}); 
} 

現在我想爲安裝狀態創建一條消息,允許我顯示類似於「脫機服務正在更新」的消息,如果有人正在處理此問題並知道如何操作,請告訴我。

我已經嘗試過同樣的代碼,但與 「如果(this.state === '安裝')」

「如果(this.state === '安裝'」

既不似乎工作。

回答

2

服務工作者有一個生命週期是從你的網頁完全分開的。 要安裝服務人員爲您的網站,你需要註冊。

self.addEventListener('install', function(event) { 
    // Perform install steps 
}); 

當我們安裝後,激活步驟將隨之而來,這是處理舊緩存管理的好機會。

self.addEventListener('activate', function(event) { 
    // Perform activate steps, Typically cache management. 
}); 

激活步驟後,服務人員將控制在其範圍下跌的所有頁面,但直到它再次加載已註冊的第一次服務工作者的頁面將無法控制。

一旦服務人員處於控制之下,它將處於以下兩種狀態之一:either the service worker will be terminated以節省內存,或it will handle fetch and message events發生在網頁請求或消息從您的頁面發出時。 您也可以嘗試像,

if ('serviceWorker' in navigator) { 
     navigator.serviceWorker.register('/sw.js').then(function(reg) { 
     // updatefound is fired if service-worker.js changes. 
     reg.onupdatefound = function() { 
      var installingWorker = reg.installing; 

      installingWorker.onstatechange = function() { 
      switch (installingWorker.state) { 
       case 'installed': 
       if (navigator.serviceWorker.controller) { 
        // At this point, the old content will have been purged and the fresh content will have been added to the cache. 
        // It's the perfect time to display a "New content is available; please refresh." 
        console.log('New or updated content is available.'); 
       } else { 
        // At this point, everything has been precached. 
        // It's the perfect time to display a "Content is cached for offline use." message. 
        console.log('Content is now available offline!'); 
       } 
       break; 

       case 'redundant': 
       console.error('The installing service worker became redundant.'); 
       break; 
      } 
      }; 
     }; 
     }).catch(function(e) { 
     console.error('Error during service worker registration:', e); 
     }); 
    } 
+0

正如我在OP中所說的,我已經知道如何安裝服務人員,並且我已經有一名服務人員安裝,我不需要編寫代碼。我需要的是在UI中顯示更新通知的一種方式(IE:不是控制檯日誌,實際網頁),就像您在OP中所述的那樣,您可以激活它。 – NGriffin

+0

區分更新與首次安裝正是我所需要的'navigator.serviceWorker.controller'檢查。謝謝! – salbahra

0

看看在live flowchart demo上ServiceWorker食譜,並在使用電報通知用戶當有更新的code snippet

+0

出於某種原因,您上面鏈接的頁面不會在我的手機甚至iPad上滾動。 – marvindanig

+1

我在ServiceWorker Cookbook repo中提交了一個問題(https://github.com/mozilla/serviceworker-cookbook/issues/254)。如果可以,請添加更多的細節問題。 – Marco