如何在service-worker.js中更新动态url

How to Update dynamic url in service-worker.js

本文关键字:更新 动态 url js service-worker      更新时间:2023-09-26
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中获得动态URL ?

我正在调用'sync'事件。我想动态传递获取URL ..总是点击提交按钮,我得到不同的URL,然后我想通过'sync'事件在获取方法中传递动态URL。

你可以使用IndexedDB或localforage这样的包装器在客户端和Service Worker之间共享信息。所以在service worker中,你可以这样读取数据:

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);
      });
  }
}