1

I am making a PWA where users can answer the forms. I want it to make also offline, so when a user fills out a form and does not have the internet connection, the reply will be uploaded when he is back online. For this, I want to catch the requests and send them when online. I wanted to base it on the following tutorial:

https://serviceworke.rs/request-deferrer_service-worker_doc.html

I have managed to implement the localStorage and ServiceWorker, but it seems the post messages are not caught correctly.

Here is the core function:

function tryOrFallback(fakeResponse) {
  // Return a handler that...
  return function(req, res) {
    // If offline, enqueue and answer with the fake response.

    if (!navigator.onLine) {
      console.log('No network availability, enqueuing');
      return;
      // return enqueue(req).then(function() {
      //   // As the fake response will be reused but Response objects
      //   // are one use only, we need to clone it each time we use it.
      //   return fakeResponse.clone();
      // });
    }
    console.log("LET'S FLUSH");
    // If online, flush the queue and answer from network.
    console.log('Network available! Flushing queue.');
    return flushQueue().then(function() {
      return fetch(req);
    });
  };
}

I use it with:

worker.post("mypath/add", tryOrFallback(new Response(null, {
  status: 212,
  body: JSON.stringify({
    message: "HELLO"
  }),
})));

The path is correct. It detects when the actual post event happens. However, I can't access the actual request (the one displayed in try or fallback "req" is basically empty) and the response, when displayed, has the custom status, but does not contain the message (the body is empty). So somehow I can detect when the POST is happening, but I can't get the actual message.

How to fix it?

Thank you in advance,

Grzegorz

1 Answer 1

1

Regarding your sample code, the way you're constructing your new Response is incorrect; you're supplying null for the response body. If you change it to the following, you're more likely to see what you're expecting:

new Response(JSON.stringify({message: "HELLO"}), {
  status: 212,
});

But, for the use case you describe, I think the best solution would be to use the Background Sync API inside of your service worker. It will automatically take care of retrying your failed POST periodically.

Background Sync is currently only available in Chrome, so if you're concerned about that, or if you would prefer not to write all the code for it by hand, you could use the background sync library provided as part of the Workbox project. It will automatically fall back to explicit retries whenever the real Background Sync API isn't available.

2

Not the answer you're looking for? Browse other questions tagged or ask your own question.