从服务工作者访问localStorage [英] Access localStorage from service worker

查看:109
本文介绍了从服务工作者访问localStorage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定期从我的服务工作者调用API来发送存储在localStorage中的数据。当用户浏览我的网站时,将生成此数据并将其保存在localStorage中。考虑一下像在localStorage中保存统计信息并定期通过服务工作者发送它。我该怎么做?我知道我无法从服务工作者访问localStorage,并且必须使用postMessage API。任何帮助都将受到高度赞赏。

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.

推荐答案

您无法从webworker进程访问localStorage(以及sessionStorage),结果将是 undefined ,这是出于安全原因。

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

您需要使用 postMessage()返回Worker的原始代码,并将该代码存储在localStorage中。

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

您应该使用 localStorage.setItem () localStorage.getItem()从本地存储中保存并获取数据。

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

更多信息:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆