简体   繁体   中英

How to Update dynamic url in service-worker.js

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

How can I get dynamic URL in service-worker.js?

I am calling 'sync' event. I want pass fetch URL dynamically..always click submit button I am getting different URL, then I want pass dynamic URL in fetch method via 'sync' event.

Please guide me.

You can share information between the client and the Service Worker by using IndexedDB or a wrapper such as localforage . So in your service worker you could read the data this way:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM