从 webWorker 访问 localStorage

发布于 2024-11-10 05:46:44 字数 68 浏览 1 评论 0原文

WebWorker 可以访问 localStorage 吗?

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

Can a WebWorker access the localStorage?

If not why not? Is it problematic from a security stand point?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

请远离我 2024-11-17 05:46:45

Web 工作人员只能访问以下内容:

因此,Web Worker 无法访问窗口或父对象您无法访问 localStorage

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

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

Web workers only have access to the following:

The window or parent objects are not accessible from a Web worker therefore you can't access the localStorage.

To communicate between window and the workerglobalscope you may use postMessage() function and onmessage event.

Accessing the DOM and window would not be thread safe, since the child thread would have the same privileges as its parent.

唱一曲作罢 2024-11-17 05:46:45

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

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

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

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.

浅笑轻吟梦一曲 2024-11-17 05:46:45

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

2021 年 4 月 9 日编辑:

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

2020 年 4 月 21 日编辑:

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

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


**August 2019 EDIT:**

有一个提议的 API 可能会在未来的某个时候发布(尽管它目前在 Chrome Canary 中可用,并且实验性网络功能标志已打开)。这就是所谓的KV存储(KV是Key Value的缩写)。它具有与 localStorage API 几乎相同的接口,并且将包含在 JavaScript 模块中。它是基于 indexeddb API 构建的,但具有更简单的 API。查看 规范 看来这也适用于 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() 
      } 
    }
  });
} 

You can use IndexedDB in WebWorkers which is a way to store things locally in a key value store. It is not the same as localStorage, but it has similar use cases and can hold quite a lot of data. We use IndexedDB in WebWorkers at my work.

April 9th, 2021 EDIT:

For a minimal library that using indexeddb mirrors the local storage api but uses async rather than sync apis you could use idb-keyval which is located here. When writing large amounts of data it's better to use an async api like the above in JS, because it allows you to not block the thread.

April 21, 2020 EDIT:

The below edit for August 2019 no longer applies, it included information on the KV storage api which was an API that mirrored the localStorage API that was async and meant to be built on top of the Indexeddb API, as pointed out by @hoogw the KV Storage API is not currently being worked on to quote the KV storage spec:

Work on this [KV strorage] specification is currently suspended, as no browser teams (including the Chromium project, which originated the proposal) are currently indicating interest in implementing it.


**August 2019 EDIT:**

There is a proposed API that might be out sometime in the future (although it's currently available in Chrome Canary with the experimental web features flag turned on). It's called KV Storage (KV is short for Key Value). It has an almost identical interface to the localStorage API and will come in JavaScript modules. It is built off of the indexeddb API, but has a much simpler API. Looking at the Spec it appears this is going to work in WebWorkers as well. For examples how to use it see the github page of the spec. Here is one such example:

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");
});

Here's the tests passing in Chrome Canary:

enter image description here

Although not necessary to use the kv-storage api the below code is the testing framework used for the above code:

// ./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() 
      } 
    }
  });
} 

凉墨 2024-11-17 05:46:45

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

2019 年 12 月。kvStorage 目前不是,并且将会将来 Chrome 也不会支持。

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

kvStorage is a good alternative, however,

Dec, 2019. kvStorage currently is NOT, and will NOT be supported in chrome in future as well.

Work on this specification is currently suspended, as no browser teams (including the Chromium project, which originated the proposal) are currently indicating interest in implementing it.

无人问我粥可暖 2024-11-17 05:46:45

Partytown 可以在这里提供帮助 - https://github.com/builderio/partytown

有了它,你可以阅读/从工作线程写入主线程数据,无需来回构建一堆postMessage协议

Partytown can help here - https://github.com/builderio/partytown

With it, you can read/write main thread data from the worker thread, without having to build a bunch of postMessage protocols back and forth

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文