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 service worker and will have to use the postMessage API. Any help would be highly appreciated.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
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.Use should use
localStorage.setItem()
andlocalStorage.getItem()
to save and get data from local storage.More infos:
Worker.postMessage()
Window.localStorage
Pseudo code below, hoping to get you start.
https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers says
Also there is a bit of discussion here: How do I access the local storage using service workers in angular?