且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Chrome 扩展 - 内容安全策略 - 执行内联代码

更新时间:2023-12-05 18:42:10

不,这不可能放宽此政策. unsafe-inline 被 Chrome 特别忽略自清单版本 2 以来的扩展.

No, this is not possible to relax this policy. unsafe-inline is specifically ignored by Chrome Extensions since manifest version 2.

文档(重点是我的):

没有机制可以放宽对执行内联 JavaScript 的限制.特别是,设置包含unsafe-inline"的脚本策略将不起作用.

There is no mechanism for relaxing the restriction against executing inline JavaScript. In particular, setting a script policy that includes 'unsafe-inline' will have no effect.

错误消息提到了几种可能的方法,但文档明确指出没有 CSP 将允许内联脚本,而忽略 unsafe-inline 只是其中一种措施.

The error message mentions several possible ways, but the docs are clear that no CSP will allow inline scripting, and ignoring unsafe-inline is but one of the measures.

从 Chrome 46 开始,可以通过在政策中指定源代码的 base64 编码哈希来将内联脚本列入白名单.该散列必须以使用的散列算法(sha256、sha384 或 sha512)作为前缀.有关示例,请参阅元素的哈希用法.

As of Chrome 46, inline scripts can be whitelisted by specifying the base64-encoded hash of the source code in the policy. This hash must be prefixed by the used hash algorithm (sha256, sha384 or sha512). See Hash usage for elements for an example.

请参阅此答案以更深入地了解白名单.

See this answer for more in-depth look at whitelisting.