0

I came across following lines on the service worker MDN documentation. https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API under service worker usage.

What it is that is causing local storage inaccessible inside service worker

It is designed to be fully async; as a consequence, APIs such as synchronous XHR and localStorage can't be used inside a service worker.

Ajay S
  • 48,003
  • 27
  • 91
  • 111
Akshay Vijay Jain
  • 13,461
  • 8
  • 60
  • 73
  • `localStorage` and `sessionStorage` are undefined in webworker process. see here http://stackoverflow.com/a/6179599/1741671 – Ajay S May 22 '17 at 06:02
  • yes they are undefined because webworker runs in DedicatedWorkerGlobalScope (i.e. a context) different from our regular context window. This might be the reason. – Akshay Vijay Jain May 22 '17 at 06:29
  • But the documentation, the reason to be "It is designed to be fully async" this makes me wonder, what role async is playing in not allowing localStorage to be used inside the ServiceWorkerGlobalScope – Akshay Vijay Jain May 22 '17 at 06:29

1 Answers1

1

Synchronous APIs that access the file system (or the network) could block the service worker's thread for an indeterminate period of time. This could prevent the service worker from doing useful work, like responding to other events, while waiting for the synchronous operation to complete.

If you take a look at the documentation for the LocalStorage API, you'll see that all of its methods (setItem, getItem, etc.) are synchronous. If they were asynchronous, then they'd either take a callback, like the IndexedDB API, or they're return a Promise, like the Cache Storage API.

Both the IndexedDB and Cache Storage APIs are available in service workers.

Jeff Posnick
  • 53,580
  • 14
  • 141
  • 167