javascript - 为什么我可以获取此跨源文件,但无法从中创建 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
解决方案
请记住,Content Security Policy
控制哪些源可以由各种浏览器机制加载。特别是我需要通配符worker-src
指令:https ://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/worker-src
推荐阅读
- laravel - 优化 dev Homestead 以减少(6 秒)长的应用程序加载时间
- c++ - 嵌套模板歧义
- c# - 填充未应用于字符串
- r - 在环境中的数据框列上应用
- ruby - Ruby 中未处理的异常
- ms-access - 我可以为我的 odbc 连接的 Access 数据库设置刷新间隔吗?
- javascript - Canvas Context.drawImage() 在 UpdatePosition() 上留下 Sprite 的副本
- javascript - 使用 PUT 方法时 body 不使用 Koa 传递
- c# - 如何在 C# 中使用用户输入创建类及其属性的实例
- android - 错误:未找到自定义方法的 Gradle DSL 方法