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

How to set Content-Security-Policy for Web Workers to work in Edge / Safari?

我在尝试使用 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);

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