gpt4 book ai didi

javascript - 如何为 Web Worker 设置 Content-Security-Policy 以在 Edge/Safari 中工作?

转载 作者:搜寻专家 更新时间:2023-11-01 04:34:38 25 4
gpt4 key购买 nike

我在尝试使用 Web Worker 时不断从 Edge 和 Safari 返回错误代码:18,SecurityError。然而,工作人员在 Firefox/Chrome 中很好。我正在使用一个内联工作程序,我将零依赖数据处理函数传递给该工作程序。

我的 CSP 看起来:

add_header Content-Security-Policy "default-src 'self'; worker-src 'self' 'inline' *.example.com";

我可以自己添加其他有用的东西,比如本地样式表和 googleapis.com,但我很好奇如何让 Worker 不抛出安全错误

片段来自 worker method

// Create an "inline" worker (1:1 at definition time)
const worker = new Worker(
// Use a data URI for the worker's src. It inlines the target function and an RPC handler:
'data:,$$='+asyncFunction+';onmessage='+(e => {
/* global $$ */

// Invoking within then() captures exceptions in the supplied async function as rejections
Promise.resolve(e.data[1]).then(
v => $$.apply($$, v)
).then(
// success handler - callback(id, SUCCESS(0), result)
// if `d` is transferable transfer zero-copy
d => {
postMessage([e.data[0], 0, d], [d].filter(x => (
(x instanceof ArrayBuffer) ||
(x instanceof MessagePort) ||
(x instanceof ImageBitmap)
)));
},
// error handler - callback(id, ERROR(1), error)
er => { postMessage([e.data[0], 1, '' + er]); }
);
})
);

Edge 为工作人员抛出此错误:

  [object DOMException]: {code: 18, message: "SecurityError", name: 
"SecurityError"}
code: 18
message: "SecurityError"
name: "SecurityError"

最佳答案

我不确定为什么数据 url 会导致安全错误,但您可以使用 URL.createObjectURL 加载工作脚本,它似乎在 Edge 中正常工作(我没有测试它在 safari 中)。

这是它的样子:

// Create the worker script as a string
const script = '$$='+asyncFunction+';onmessage='+(e => {
/* global $$ */

// Invoking within then() captures exceptions in the supplied async function as rejections
Promise.resolve(e.data[1]).then(
v => $$.apply($$, v)
).then(
// success handler - callback(id, SUCCESS(0), result)
// if `d` is transferable transfer zero-copy
d => {
postMessage([e.data[0], 0, d], [d].filter(x => (
(x instanceof ArrayBuffer) ||
(x instanceof MessagePort) ||
(x instanceof ImageBitmap)
)));
},
// error handler - callback(id, ERROR(1), error)
er => { postMessage([e.data[0], 1, '' + er]); }
);
});

// Create a local url to load the worker
const blob = new Blob([script]);
const workerUrl = URL.createObjectURL(blob);
const worker = new Worker(workerUrl);

如果您需要任何说明,请告诉我!

关于javascript - 如何为 Web Worker 设置 Content-Security-Policy 以在 Edge/Safari 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54714860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com