Content Security Policy未拦截第三方JavaScript加载,如何解决?
解决Content Security Policy无法拦截第三方资源的问题
你当前设置的CSP规则Content-Security-Policy: default-src 'self' https: 之所以拦不住第三方JS/CSS,核心原因是规则里的https:允许了所有HTTPS协议的外部资源,不管域名是不是第三方的。
要实现拦截第三方库的目标,你需要调整CSP规则:
- 移除
default-src中的https:,只保留'self',让默认规则仅允许本站资源:Content-Security-Policy: default-src 'self' - 如果你的网站确实需要加载特定的第三方资源(比如某个可信CDN的库),不要用通配符,而是在对应的资源类型规则里明确指定允许的域名,比如:
这样既允许必要的可信第三方资源,又拦截其他未被指定的外部资源。Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-cdn.example.com; style-src 'self' https://trusted-cdn.example.com - 调试阶段可以添加
report-only模式(仅上报违规行为不拦截),先验证规则是否符合预期:Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self' https://trusted-cdn.example.com; style-src 'self' https://trusted-cdn.example.com; report-uri /csp-violation-report-endpoint
内容的提问来源于stack exchange,提问作者StaticMethod
相关产品推荐
相关产品推荐

