Akshay Vijay Jain
Akshay Vijay Jain

Reputation: 15945

Service worker's architecture

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.

Upvotes: 0

Views: 320

Answers (1)

Jeff Posnick
Jeff Posnick

Reputation: 56074

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.

Upvotes: 1

Related Questions