【发布时间】:2020-05-10 11:56:49
【问题描述】:
我正在创建一个 Chrome 扩展程序,它修改服务器提供的脚本(我无法控制)以向网站添加新功能,我有以下想法:
- 通过 WebRequest、webRequestBlocking 阻止原始脚本。
- 将被阻止脚本的 url 发送到注入页面的脚本。
- 从页面脚本中获取此 url。
- 编辑部分代码(字符串)。
- 评估字符串。
(另一种工作方式是将其重定向到本地修改脚本return { redirectUrl: chrome.extension.getURL("modified.js") };,在 Chrome 扩展文件夹内,但随后无法即时修改它,这就是我想评估修改后脚本的原因)
当我尝试在第 5 步中评估字符串时,它显示:...'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'nonce-DFX4zDtBDF32343LjE2DFKMs' 'self' https://website.com"。
我尝试使用 webRequest.onHeadersReceived 来查看是否可以更改 CSP 标头(正如一些答案所建议的那样:Edit Content Security Policy in onHeadersReceived),但没有“content-security-policy”标头。
我可以看到一个内容安全策略元标记(我省略了除“script-src”之外的所有内容):
<meta http-equiv="Content-Security-Policy" content="script-src 'nonce-DFX4zDtBDF32343LjE2DFKMs' 'self' https://website.com; base-uri 'none';">
根据这个答案 (https://stackoverflow.com/a/27324485/10364842),Chrome 扩展程序无法覆盖网页的 CSP。但有人回复:I know this is incredibly old, but I came across it while trying to inject Artoo.js into a page. The chrome extension does indeed allow you to modify the page you're looking at and let any content through.
Eval 在内容脚本中工作,但我需要在页面上下文中执行脚本,因为它取决于全局范围。
我想知道是否可以通过 Chrome 扩展程序更改网页的 CSP,或者是否有任何其他方法可以仅通过 Chrome 扩展程序完成此操作?
【问题讨论】:
-
我不知道是否可以让扩展程序更改页面内容以更改该
meta元素中 CSP 策略的值 - 但如果事实证明这实际上是不可能的,那么没有其他可行的解决方案。原因是,即使您将 Content-Security-Policy 响应标头注入到响应中,该meta元素中的 CSP 策略仍将被应用。有关解释,请参阅stackoverflow.com/a/51153816/441757 的答案 -
Chrome 中的 chrome.webRequest API 无法更改服务器响应正文,只有 Firefox 提供了这样的功能。 Chrome 中唯一可能的解决方法是在选项卡开始加载时使用 chrome.debugger API(例如,在 chrome.webNavigation.onCommitted 中)通过 Fetch.getResponseBody 和 Fetch.takeResponseBodyAsStream 修补响应(请参阅CDP)。
-
谢谢!这是一个通过修改响应正文删除 CSP 元标记的扩展:github.com/Sentero-esp12/… 它使用调试器和 Fetch API
标签: javascript google-chrome google-chrome-extension content-security-policy