Accessing Localstorage from a Webworker

Accessing localStorage from a webWorker

No, localStorage and sessionStorage are both undefined in a webworker process.

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

Interestingly, a webworker can use an AJAX call to send/retrieve info to/from a server, so that may open possibilities, depending on what you're trying to do.

Access localStorage from service worker

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)

localStorage usage in a web Worker

I understood, that DOM and window objects are not accessible from a worker, but the following article had introduced a bit of doubt in my mind: In defense of localStorage.

Looking at the article more critically and with further research, I understand confidently that the web storage objects are not accessible to a worker. Back to the article, it discussed what can be a possible capability of the API in the future, not it's present capability.

The other article that helped clarify my doubt states:

"For instance, since you don’t have access to the window object from a worker, you won’t be able to access the Local Storage (which doesn’t seem to be thread-safe anyway)."

Using WebWorkers just for LocalStorage?

I believe most browsers will implement web storage as in memory storage. So you won't get performance benefit over using web worker.

To handle multiple tabs/browser you will use storage events.

As you can see, localStorage is not slow, but in-consistant sometimes on read and write. It is nothing you can do except to use transactional storage like IndexedDB or WebSQL.

Web worker with persistent data

Workers can use IndexedDB for persistent storage.

Workers can’t use Web Storage (localStorage) but there are good small IndexedDB libs, like Dexie—which can be used in workers & which makes using IndexedDB nearly as easy as localStorage.



Related Topics



Leave a reply



Submit