Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access localStorage from service worker

I want to periodically call an API from my service worker to send data stored in the localStorage. This data will be produced and saved in localStorage when a user browses my website. Consider it something like saving stats in localStorage and sending it periodically through the service worker. How should I do this? I understand that I can't access localStorage from the service worker and will have to use the postMessage API. Any help would be highly appreciated.

like image 813
Faiz Avatar asked Nov 30 '16 11:11

Faiz


People also ask

Can service workers access localStorage?

Note: localStorage works in a similar way to service worker cache, but it is synchronous, so not allowed in service workers.

Which client side storage API is accessible by service workers?

Cache API The API is typically used in service workers to cache network responses for progressive web apps.

Can PWA access local storage?

Note: TWA shares the browser data like cookies and localStorage inside app, so if you are logged in inside a browser then you'll automatically be logged in TWA app as well.


2 Answers

You cannot access localStorage (and also sessionStorage) from a webworker process, they result will be undefined, this is for security reasons.

You need to use postMessage() back to the Worker's originating code, and have that code store the data in localStorage.

You should use localStorage.setItem() and localStorage.getItem() to save and get data from local storage.

More info:

Worker.postMessage()

Window.localStorage

Pseudo code below, hoping it gets you started:

 // include your worker  var myWorker = new Worker('YourWorker.js'),    data,    changeData = function() {      // save data to local storage      localStorage.setItem('data', (new Date).getTime().toString());      // get data from local storage      data = localStorage.getItem('data');      sendToWorker();    },    sendToWorker = function() {      // send data to your worker      myWorker.postMessage({        data: data      });    };  setInterval(changeData, 1000) 
like image 141
GibboK Avatar answered Sep 22 '22 04:09

GibboK


I've been using this package called localforage that provides a localStorage-like interface that wraps around IndexedDB. https://github.com/localForage/localForage

You can then import it by placing it in your public directory, so it is served by your webserver, and then calling: self.importScripts('localforage.js'); within your service worker.

like image 45
Allen Avatar answered Sep 21 '22 04:09

Allen