【发布时间】:2023-02-26 04:35:21
【问题描述】:
我正在将我的扩展从 V2 迁移到 V3。现在除了一件事外一切正常。在我的 V2 版本中我做了
const actualCode = '(' + function () { 'console.log("demo");' } + `)();`;
const script = document.createElement('script');
script.textContent = actualCode;
(document.head || document.documentElement).appendChild(script);
script.remove();
请注意,console.log("demo") 是对我需要注入的内容的简化 :)
我需要为我的 chrome-extension-magic 注入一些 javascript。
现在,在 V3 中这不再起作用了。我在我的 devtools-console 中收到以下错误
content.js:23114
Refused to execute inline script because it violates the following
ContentSecurity Policy directive: "script-src 'self'". Either the
'unsafe-inline' keyword, a hash ('sha256-tN52+5...6d2I/Szq8='), or a nonce
('nonce-...') is required to enable inline execution.
在迁移指南中,我注意到了这一部分
"content_security_policy": {
"extension_pages": "...",
"sandbox": "..."
}
但是那里没有太多描述,所以这对我来说很神奇。所以我希望有人知道可以帮助我吗?
【问题讨论】:
-
使用单独的文件,如method 1 here 所示。它异步运行,因此它可能比页面的某些脚本运行得晚。将来 chrome.scripting.registerContentScripts 将允许指定
world。 -
就是这样,thnx。我已经对其进行了测试,但不幸的是,就我而言,该解决方案不起作用。在我的例子中,我需要在页面脚本运行之前运行注入的脚本。我已经测试了这个解决方案并注意到注入的脚本现在运行得太晚了:(
-
你必须继续使用 MV2。
-
是的,我得出了完全相同的结论
-
我看到你用它来覆盖 XHR/fetch,所以这里有一个替代方案(以防站点不使用已弃用的同步 XHR):覆盖 XMLHttpRequest.prototype.response getter(也是 responseText)和 Response.prototype.text getter(也是 json , blob, arrayBuffer, formData) 通过 Object.getOwnPropertyDescriptor + Object.defineProperty。这些 getter 在远程服务器响应后使用,因此您的脚本应该总是更早运行。
标签: javascript google-chrome-extension migration chrome-extension-manifest-v3