service-workerbrowser-cacheservice-worker-events

How to store a list of querys and send them to mySQL when online?


I'm trying to build a webapp that will work offline.
I found JS Service worker and i have now implemented it in my app to store some static pages.

Now i'd like to build a HTML FORM where the user fills in stuff that will be saved to the cache if the user is offline.. but directly sends to mysql when the user is online.

It will be like a list with querys that will execute when user comes online.

How can i save a query string to the cache, and then check if online and send it with Ajax? to php and mySQL.

First off, how do i save a query string to the cache?
Second.. how do i find out when online and then fetch the query string from the cache?

This is what i got to cache my pages:

importScripts('cache-polyfill.js');

self.addEventListener('install', function(e) {
e.waitUntil(
  caches.open('offlineList').then(function(cache) {
    return cache.addAll([
      '/app/offline_content/'
    ]);
  })
);
});

self.addEventListener('fetch', function(event) {
console.log(event.request.url);

event.respondWith(
  caches.match(event.request).then(function(response) {
    return response || fetch(event.request);
  })
);
});

EDIT

I'm now reading up on HTML/JS "localStorage"..


Solution

  • Well i solved this by adding data to localStorage:

    //ADD DATA 
    localStorage.setItem(key, JSON.stringify(value));
    

    Then i check for internet connection:

    //CHECK INTERNET CONNECTION
    const checkOnlineStatus = async () => { //console.log('CHECKING INTERNET..');
        try {
          const online = await fetch("/img.gif");
          return online.status >= 200 && online.status < 300; // either true or false
        } catch (err) {
          return false; // definitely offline
        }
    };
    
    const result = await checkOnlineStatus();
    result ? updateMysql() : console.log('NO INTERNET..');
    

    In the updateMysql() function i load all the localStorage and send it with ajax to php and mySQL.

    var query = JSON.parse(localStorage.getItem(key));