首页 > 解决方案 > 为什么我可以获取此跨源文件,但无法从中创建 Worker?

问题描述

有问题的文件是这个:http://web-reports-static.s3.us-east-2.amazonaws.com/_next/e02d25753c0f34f5e22c.worker.js

该文件托管在允许任何域获取该文件的 s3 存储桶中。我还设置了以下 CORS 策略:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
</CORSRule>
</CORSConfiguration>

您可以在任何网站的控制台中尝试它(例如,在 stackoverflow 上打开开发工具)。

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // Typical action to be performed when the document is ready:;
      console.log(xhttp.responseText)
    }
};
xhttp.open("GET", "http://web-reports-static.s3.us-east-2.amazonaws.com/_next/e02d25753c0f34f5e22c.worker.js", true)
xhttp.send()

但是直接使用它来构造一个 Worker 会导致错误:

> new Worker("http://web-reports-static.s3.us-east-2.amazonaws.com/_next/e02d25753c0f34f5e22c.worker.js")

VM1925:1 Uncaught DOMException: Failed to construct 'Worker': Script at 'http://web-reports-static.s3.us-east-2.amazonaws.com/_next/e02d25753c0f34f5e22c.worker.js' cannot be accessed from origin 'https://stackoverflow.com'.
    at <anonymous>:1:1
(anonymous) @ VM1925:1

标签: javascriptamazon-s3corsworker-loader

解决方案


请记住,Content Security Policy控制哪些源可以由各种浏览器机制加载。特别是我需要通配符worker-src指令:https ://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/worker-src


推荐阅读