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

问题描述 投票:5回答:1

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

我的CSP看起来:

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

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

来自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"
javascript web-worker content-security-policy nginx-config
1个回答
1
投票

我不确定为什么数据网址会导致安全错误,但你可以使用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);

如果您需要任何澄清,请告诉我!

© www.soinside.com 2019 - 2024. All rights reserved.