CSP img-src规则下Firefox与Chrome图片加载行为差异咨询
问题描述
我正在将一款Chrome扩展移植至Firefox平台使用,该扩展的功能为在Github网站页面上展示关联Jira工单的相关信息。
Chrome环境下运行效果如下:
完成少量适配修改后,扩展大部分功能运行正常,但无法加载来自Atlassian(Jira)站点的图片资源,Firefox环境下异常效果如下:
经排查,该问题由CSP拦截导致,控制台抛出如下错误:
Content Security Policy: The page's settings blocked the loading of a resource at https://myproject.atlassian.net/images/icons/statuses/generic.png ("img-src").
我查阅资料确认,Content-Security-Policy: img-src特性已被Chrome和Firefox支持近10年,不清楚两款浏览器为何出现行为差异。当前页面返回的content-security-policy响应头中img-src规则配置如下:
img-src 'self' data: github.githubassets.com identicons.github.com github-cloud.s3.amazonaws.com secured-user-images.githubusercontent.com/ github-production-user-asset-6210df.s3.amazonaws.com *.githubusercontent.com;
完整CSP策略如下:
default-src 'none'; base-uri 'self'; block-all-mixed-content; child-src github.com/assets-cdn/worker/ gist.github.com/assets-cdn/worker/; connect-src 'self' uploads.github.com objects-origin.githubusercontent.com www.githubstatus.com collector.github.com raw.githubusercontent.com api.github.com github-cloud.s3.amazonaws.com github-production-repository-file-5c1aeb.s3.amazonaws.com github-production-upload-manifest-file-7fdce7.s3.amazonaws.com github-production-user-asset-6210df.s3.amazonaws.com cdn.optimize…ithubusercontent.com notebooks.githubusercontent.com; img-src 'self' data: github.githubassets.com identicons.github.com github-cloud.s3.amazonaws.com secured-user-images.githubusercontent.com/ github-production-user-asset-6210df.s3.amazonaws.com *.githubusercontent.com; manifest-src 'self'; media-src github.com user-images.githubusercontent.com/; script-src github.githubassets.com; style-src 'unsafe-inline' github.githubassets.com; worker-src github.com/assets-cdn/worker/ gist.github.com/assets-cdn/worker/
我可以理解Firefox按照上述img-src规则拦截Atlassian域名图片的行为,但不清楚为何相同CSP策略下Chrome不会拦截该资源、可正常加载图片,特此咨询两款浏览器CSP执行逻辑出现该差异的具体原因。
问题解答
差异核心原因
这个差异和CSP标准本身的兼容性没有关系,本质是两款浏览器对扩展注入页面的资源的CSP校验默认规则不一致:
- Chrome对Manifest V2扩展长期保留了CSP豁免特权:只要扩展在
manifest.json的permissions字段中声明了对应域名的跨域访问权限,扩展通过内容脚本插入到页面的DOM资源(比如你添加的Jira图标img标签),不会被目标页面自身的CSP规则拦截,因此图片可以正常加载。这是Chrome扩展生态延续多年的设计逻辑,优先保障扩展功能可用性。 - Firefox从扩展体系设计之初就没有设置这类默认豁免:所有插入到页面DOM树的资源,无论来自页面本身还是扩展注入,默认都要接受页面CSP规则的校验。Github的CSP img-src白名单没有包含Atlassian域名,因此图片加载被直接拦截。
适配Firefox的可行方案
以下两个方案不需要用户修改浏览器配置,即可实现双浏览器兼容:
- 方案1:修改页面返回的CSP响应头。在扩展中调用
declarativeNetRequestAPI(相比老的webRequestAPI权限要求更低、性能更好)拦截Github页面的响应,将*.atlassian.net追加到content-security-policy头的img-src规则段末尾,浏览器就会放行Jira域名下的图片资源。 - 方案2:将图片转base64格式内嵌。在扩展的后台脚本中先发起请求拉取Jira图标资源,将响应内容转为base64格式的data URI,再将这个data URI作为img标签的src插入页面。由于Github的CSP img-src规则明确允许
data:类型资源,该方案不需要修改CSP规则,兼容性最稳定,也不会触发额外的安全提示。
内容的提问来源于stack exchange,提问作者Bouffe
相关产品推荐
相关产品推荐

