2016-04-24 37 views
1

在Chrome Mac上。我正在嘗試註冊ServiceWorker併爲其設置一個變量。當我調用register()並且以前沒有安裝服務工作者時,「active」屬性似乎立即設置爲null,然後很快就會初始化(異步?)。ServiceWorkerRegistration.active未設置爲第一次(Chrome)

var sw = null; 
navigator.serviceWorker.register('preview/sw.js', {scope: 'preview/'}). 
    then(function(registration) { 
     console.dir(registration); 
     sw = registration.active; 
     if (!sw) { 
      console.log('wat'); 
      console.dir(registration); 
     } 
    }); 

換句話說,我第一次安裝服務人員時進入了if-block。控制檯顯示活動屬性在console.dir()命令中設置爲等於ServiceWorker,但sw變量爲null。

刷新頁面可修復問題。有人知道可能會造成這種情況嗎?

回答

0

服務人員已註冊,但它尚未激活,它尚未控制您的頁面。

如果希望服務人員變爲活動狀態,則可以在install事件處理函數中調用skipWaiting函數。

如果希望服務工作人員在其變爲活動狀態時立即控制頁面,則可以使用activate事件處理函數中的Clients.claim函數。

您可以在ServiceWorker Cookbook Immediate Claim recipe中看到一個示例。

3

對於您所描述的第一次訪問,註冊尚未active當該承諾解決但它是「正在安裝」,因此註冊的installing屬性將返回一個服務工作者。

由於沒有服務人員處於waiting狀態,因此它將轉換爲activating,然後轉換爲active。所以你是對的,註冊財產最初不是active但刷新,它會。

將下面的代碼說明:

navigator.serviceWorker.register('/serviceworker.js').then(onRegistration); 

function onRegistration(registration) { 
    if (registration.waiting) { 
    console.log('waiting', registration.waiting); 
    registration.waiting.addEventListener('statechange', onStateChange('waiting')); 
    } 

    if (registration.installing) { 
    console.log('installing', registration.installing); 
    registration.installing.addEventListener('statechange', onStateChange('installing')); 
    } 

    if (registration.active) { 
    console.log('active', registration.active); 
    registration.active.addEventListener('statechange', onStateChange('active')); 
    } 
} 

function onStateChange(from) { 
    return function(e) { 
    console.log('statechange', from, 'to', e.target.state); 
    } 
} 

在第一次訪問時,console.log輸出將是:

installing ServiceWorker {scriptURL: "http://...", state: "installing", onstatechange: null, onerror: null} 
statechange initial state installing changed to installed 
statechange initial state installing changed to activating 
statechange initial state installing changed to activated 

,你觀察到的狀態的變化同步發生。