2016-11-08 15 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); 
     }); 
    } 
}