2016-11-08 16 views
0
self.addEventListener('sync', function(event) { 
    console.log('firing: sync'); 

    if (event.tag == 'image-fetch') { 
     console.log('sync event fired'); 
     event.waitUntil(fetchurl()); 
    } 
}); 

function fetchurl() 
{ 
    console.log('firing: doSomeStuff()'); 

    /* fetch dynamic url */ 
    fetch('https://localhost/Service-Workers-BackgroundSync/server.php') 
    .then(function(response) { 
     return response; 
    }) 
    .then(function(text) { 
     console.log('Request successful', text); 
    }) 
    .catch(function(error) { 
     console.log('Request failed', error); 
    }); 
} 

如何在service-worker.js中獲取動態網址?如何更新service-worker.js中的動態網址

我打電話'同步'事件。我想要動態地傳遞抓取網址..一直點擊提交按鈕我得到不同的網址,然後我想通過'同步'事件在抓取方法中傳遞動態網址。

請指導我。

回答

1

您可以通過使用IndexedDB或包裝器(如localforage)在客戶端和服務人員之間共享信息。所以在你的服務人員你可以這樣讀取數據:

importScripts('./lib/localforage.js'); 

function fetchurl() 
{ 
    console.log('firing: doSomeStuff()'); 
    /* get dynamic url from IndexedDB using localForage */ 
    localforage.getItem('dynamicUrl') 
    .then(function (url) { 
    fetch(url) 
     .then(function(response) { 
     return response; 
     }) 
     .then(function(text) { 
     console.log('Request successful', text); 
     }) 
     .catch(function(error) { 
     console.log('Request failed', error); 
     }); 
    } 
}