Sea*_*lly 5 javascript web-worker content-security-policy nginx-config
我一直在找回错误代码:18,尝试使用Web Worker时来自Edge和Safari的SecurityError。但是,在Firefox / Chrome中,工作人员很好。我正在使用传递零依赖数据处理函数的内联工作器。
我的CSP看起来:
add_header Content-Security-Policy "default-src 'self'; worker-src 'self' 'inline' *.example.com";
Run Code Online (Sandbox Code Playgroud)
我可以自己添加其他不错的东西,例如本地样式表和googleapis.com,但我很好奇如何使Worker不会引发安全错误
工作者方法的摘录
// 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]); }
);
})
);
Run Code Online (Sandbox Code Playgroud)
Edge为工作者抛出此错误:
[object DOMException]: {code: 18, message: "SecurityError", name:
"SecurityError"}
code: 18
message: "SecurityError"
name: "SecurityError"
Run Code Online (Sandbox Code Playgroud)
我不确定为什么数据 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);
Run Code Online (Sandbox Code Playgroud)
如果您需要任何说明,请告诉我!
| 归档时间: |
|
| 查看次数: |
130 次 |
| 最近记录: |