You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

浏览器扩展拉取GitHub原始文件的CORS及缓存问题排查

浏览器扩展拉取GitHub JSON文件的CORS问题及后续

场景与初始代码

在浏览器扩展的background.js中,我需要定期拉取GitHub公开仓库里的JSON文件。为了合理使用GitHub带宽,希望仅在文件自上次更新后有修改时才重新拉取,编写的代码如下:

url='https://raw.githubusercontent.com/LearnWebCode/json-example/master/pets-data.json';

fetch(url, {
  headers: {'If-Modified-Since': 'Wed, 15 Aug 2022 18:30:00 GMT'}}
).then(response => response.json())
.then(json => console.log('Loaded: ', json));

遇到的CORS错误

执行代码时触发了CORS限制错误:

Access to fetch at
'https://raw.githubusercontent.com/LearnWebCode/json-example/master/pets-data.json'
from origin 'chrome-extension://...'
has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
It does not have HTTP ok status.

尝试添加以下任意组合的请求头,均未解决问题:

'Content-Type': 'text/plain;charset=UTF-8'
'Accept': 'application/vnd.github.v3.raw'
'User-Agent': 'my_github_username/my_github_repository (Chrome 104.0.5112.79)'

改用GitHub Pages作为文件访问替代方式,同样无效。

问题更新

通过在manifest.json的host_permissions中添加raw.githubusercontent.com,已成功解决CORS错误(感谢@wOxxOm)。但If-Modified-Since头部未按预期影响服务器行为,相关细节见后续问题。

内容的提问来源于stack exchange,提问作者wass rubleff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 15:15:31