问题描述
|
WebWorker可以访问localStorage吗?
如果不是,为什么不呢?从安全角度来看有问题吗?
解决方法
不可以,在webworker进程中都未定义localStorage和sessionStorage。
您将必须将“ 0”回调回Worker的原始代码,并使该代码将数据存储在localStorage中。
有趣的是,Webworker可以使用AJAX调用来向服务器发送信息/从服务器检索信息,从而可能打开各种可能性,具体取决于您要执行的操作。
, Web工作人员只能访问以下内容:
XMLHttpRequest
应用缓存
创建其他网络工作者
navigator
物件
location
物件
setTimeout
法
clearTimeout
法
setInterval
法
clearInterval
法
importScripts
法
JSON
Worker
Web工作者无法访问该窗口或父对象,因此您无法访问ѭ11。
要在窗口和workerglobalscope
之间进行通信,可以使用postMessage()
功能和onmessage
事件。
访问DOM和窗口将不是线程安全的,因为子线程将具有与其父线程相同的特权。
, 您可以在WebWorkers中使用IndexedDB,这是一种将内容本地存储在键值存储中的方法。它与localStorage不同,但是具有相似的用例,可以保存大量数据。在我的工作中,我们在WebWorkers中使用IndexedDB。
2019年8月编辑:
有一个建议的API可能会在将来的某个时候发布(尽管Chrome Canary中目前启用了实验性网络功能标记,但该API目前可用)。它称为KV存储(KV是键值的缩写)。它具有与localStorage API几乎相同的接口,并将包含在JavaScript模块中。它是基于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()
}
}
});
}
, kvStorage是一个不错的选择,但是,
2019年12月。kvStorage当前不可用,将来也不会在chrome中支持。
由于没有浏览器团队(包括发起该建议的Chromium项目)目前没有表示有兴趣实施此规范,因此目前暂未对此规范进行开发。