链接到 Xcode 项目的 repo 以测试问题:Test CORS Issue
此扩展使用 Manifest v3,我在
example.com
中有
host_permissions
"host_permissions": [
"*://example.com/*"
]
当我在
fetch("https://example.com")
中运行background.js
时,我得到这个错误:
[Error] Fetch API cannot load https://example.com/ due to access control checks.
[Error] Failed to load resource: Origin safari-web-extension://e0b5d7c7-c079-484b-8825-44d261383cb6 is not allowed by Access-Control-Allow-Origin. Status code: 200 (example.com, line 0)
在 Safari 版本 16.0(17614.1.25.9.10、17614)和 Safari 技术预览版 153(Safari 16.0、WebKit 17615.1.4.1)中测试
在我使用
chrome
命名空间的代码中(在Chrome浏览器中测试它)但是我在browser
命名空间中遇到了同样的问题。
如果我在 Chrome 浏览器中不做任何更改地运行此扩展程序,它会完美运行 (chrome://extensions/ → 加载解压)
有没有办法在不更改服务器访问控制设置的情况下避免 CORS 问题?
Manifest v2 以这种方式运行良好。
更新一:
现在使用后台脚本(在 v3 中已弃用)而不是后台服务工作者的解决方法。
而不是这个:
"background": {
"service_worker": "background.js"
},
这样做:
"background": {
"scripts": ["background.js"]
},
更新 2:如何让您的扩展同时适用于 Chrome 和 Safari?
Chrome 仅支持
"background": {
"service_worker": "background.js"
},
Safari 同时支持
service_worker
和 scripts
但是当你使用 service_worker 时它有这个 CORS 问题。
所以解决方案是在
background
字段中发送具有不同值的扩展。
来自:https://webkit.org/blog/13966/webkit-features-in-safari-16-4/#safari-web-extensions
Fixed CORS issue when doing fetch requests from a background service worker.