从 webWorker 访问 localStorage

IT技术 javascript html local-storage web-worker
2021-03-01 13:21:10

WebWorker 可以访问 localStorage 吗?

如果不是为什么不呢?从安全的角度来看有问题吗?

4个回答

网络工作者只能访问以下内容:

Web 工作者无法访问窗口或父对象,因此您无法访问localStorage.

要在窗口和窗口之间进行通信,workerglobalscope您可以使用postMessage()函数和onmessage事件。

访问 DOM 和窗口不是线程安全的,因为子线程与其父线程具有相同的权限。

但是它可以访问 indexedDB。
2021-04-19 13:21:10
并且线程安全不是 localStorage 的问题,因为它已经需要提供同步访问以容纳多个浏览器选项卡同时访问它。stackoverflow.com/questions/22001112/...
2021-04-22 13:21:10
网络工作者不能总是创建其他网络工作者(例如 Chrome 不支持此功能)...请在此处查看有关此的问题和答案
2021-04-29 13:21:10
当前在 Safari 上的网络工作者中无法访问 indexedDB
2021-05-07 13:21:10

不,localStorage 和 sessionStorage 在 webworker 进程中都未定义。

您必须postMessage()回调 Worker 的原始代码,并让该代码将数据存储在 localStorage 中。

有趣的是,网络工作者可以使用 AJAX 调用向/从服务器发送/检索信息,因此这可能会打开各种可能性,具体取决于您尝试执行的操作。

大多数环境支持 webworker 访问 indexeddb
2021-04-26 13:21:10

您可以WebWorkers使用IndexedDB这是一种将内容本地存储在键值存储中的方法。它与 localStorage 不同,但它具有类似的用例并且可以保存相当多的数据。在我的工作中,我们在 WebWorkers 中使用 IndexedDB。

2021 年 4 月 9 日编辑:

对于使用 indexeddb 镜像本地存储 api 但使用异步而不是同步 apis 的最小库,您可以使用idb-keyval它位于 here当写入大量数据时,最好在 JS 中使用像上面这样的异步 api,因为它允许您不阻塞线程。

2020 年 4 月 21 日编辑:

以下 2019 年 8 月的编辑不再适用,它包含有关 KV 存储 API 的信息,该 API 反映了异步的 localStorage API,旨在构建在 Indexeddb API 之上,正如@hoogw KV 所指出的存储 API 目前尚未用于引用KV 存储规范

该 [KV 存储] 规范的工作目前已暂停,因为目前没有浏览器团队(包括提出该提案的 Chromium 项目)表示有兴趣实施它。

**2019 年 8 月编辑:**

有一个提议的 API 可能会在未来的某个时候推出(尽管它目前在 Chrome Canary 中可用,并打开了实验性网络功能标志)。它被称为 KV 存储(KV 是 Key Value 的缩写)。它具有与 localStorage API 几乎相同的接口,并将出现在 JavaScript module中。它是基于 indexeddb API 构建的,但具有更简单的 API。查看Spec似乎这也适用于 WebWorkers。有关如何使用它的示例,请参阅规范github 页面这是一个这样的例子:

import storage, { StorageArea } from "std:kv-storage";
import {test, assert} from "./florence-test";

test("kv-storage test",async () => {
  await storage.clear()
  await storage.set("mycat", "Tom");
  assert(await storage.get("mycat") === "Tom", "storage: mycat is Tom");

  const otherStorage = new StorageArea("unique string");
  await otherStorage.clear()
  assert(await otherStorage.get("mycat") === undefined, "otherStorage: mycat is undefined");
  await otherStorage.set("mycat", "Jerry");
  assert(await otherStorage.get("mycat") === "Jerry", "otherStorage: mycat is Jerry");
});

以下是在 Chrome Canary 中通过的测试:

在此处输入图片说明

虽然没有必要使用 kv-storage api,但以下代码是用于上述代码的测试框架:

// ./florence-test.js

// Ryan Florence's Basic Testing Framework modified to support async functions
// https://twitter.com/ryanflorence/status/1162792430422200320
const lock = AsyncLock();

export async function test (name, fn) {
  // we have to lock, so that console.groups are grouped together when
  // async functions are used.
  for await (const _ of lock) {
    console.group(name);
    await fn();
    console.groupEnd(name);
  }
};

export function assert (cond, desc) {
  if (cond) {
    console.log("%c✔️", "font-size: 18px; color: green", desc);
  } else {
    console.assert(cond, desc);
  }
};

// https://codereview.stackexchange.com/questions/177935/asynclock-implementation-for-js
function AsyncLock() { 
  const p = () => new Promise(next => nextIter = next ); 
  var nextIter, next = p(); 
  const nextP = () => { const result = next; next = result.then(() => p() ); return result;} 
  nextIter(); 
  return Object.assign({}, { 
    async * [Symbol.asyncIterator] () {
      try { 
        yield nextP() 
      } finally {
      nextIter() 
      } 
    }
  });
} 
当前在 Safari 上的网络工作者中无法访问 indexedDB
2021-04-19 13:21:10
不明白为什么这被否决了,所以我投了赞成票,所以它又回到了零。LocalStorage 不能在 webworker 中使用,如果需要在浏览器中存储 IndexedDB 是在 worker 中工作的替代方案。
2021-04-28 13:21:10
2019 年 12 月。将来 chrome 将不支持 kvStorage。本规范暂停指定期限。
2021-05-16 13:21:10

kvStorage是一个不错的选择,但是,

2019 年 12 月。 kvStorage 目前不支持,将来也不支持 chrome。

该规范的工作目前已暂停,因为目前没有浏览器团队(包括提出该提案的 Chromium 项目)表示有兴趣实施它。