由于安全问题,无法使用清单 v3 在 Chrome 扩展中运行 Create-React-App

lsi*_*ons 5 google-chrome-extension content-security-policy create-react-app

我正在制作一个 chrome 扩展,它将创建一个 iframe,将其注入页面,然后在该 iframe 中运行一个 react 应用程序。我正在做的反应与应用程序中创建应用程序做出反应和一个<script/>s中build/index.html由于安全问题将不会被执行。

其中index.html包含三个<script/>s:

<script>!function(e){function r...<LONG CHUNK OF BUNDLED CODE></script>
<script src="/static/js/2.f6218dca.chunk.js"></script>
<script src="/static/js/main.c335a43f.chunk.js"></script>
Run Code Online (Sandbox Code Playgroud)

上面列出的第一个脚本是一个大的捆绑脚本,我在这里主要剪掉了。后两个似乎加载并运行良好,但我收到第一个的以下错误消息。

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-ssRao1c5f8Pf3VvQXjkNHGmrQ6+tZ7Fuaxxxxxxxxxx='), or a nonce ('nonce-...') is required to enable inline execution.
Run Code Online (Sandbox Code Playgroud)

我之前在使用 manifest v2 时遇到过这个错误,并且知道有很多答案显示了如何解决它,但它们似乎不适用于 manifest v3。如此处所述关于新的 v3 安全策略:

“script-src、object-src 和 worker-src 指令可能只有以下值:

  • 自己
  • 没有任何
  • 任何本地主机源,(http://localhost、http: //127.0.0.1或这些域上的任何端口)”

因此上面的错误信息似乎已经过时了。如果我添加'unsafe-inline''sha256-ssRao1c5f8Pf3VvQXjkNHGmrQ6+tZ7Fuaxxxxxxxxxx='到我的内容安全策略,我无法将扩展加载到 Chrome 中 - 它被拒绝并显示如下消息"'content_security_policy.extension_pages': Insecure CSP value "'unsafe-inline'" in directive 'script-src'."

此外,我似乎为其他两个脚本设置了正确的 v3 安全策略 - 我可以通过更改它并获取上述三个错误消息来验证这一点,每个脚本一个。

"content_security_policy": {
    "extension_pages": "script-src 'self'; object-src 'self'"
},
Run Code Online (Sandbox Code Playgroud)

无论如何加载捆绑的js代码的第一个脚本?或者我是否必须将它放在另一个文件中并加载它<script src="/path/to/new_file.js"...

这里还有我的内容脚本中的代码,用于创建 iframe 并将 react 应用程序注入其中,以防万一:

const modal = document.createElement('dialog');
modal.setAttribute("style", "height:40%");
modal.innerHTML =
       `<iframe id="headlineFetcher" style="height:100%"></iframe>
        <div style="position:absolute; top:0px; left:5px;">  
            <button>x</button>
        </div>`;
document.body.appendChild(modal);
const dialog = document.querySelector("dialog");
dialog.showModal();

const iframe = document.getElementById("headlineFetcher");  
iframe.src = chrome.runtime.getURL("index.html");
iframe.frameBorder = 0;
Run Code Online (Sandbox Code Playgroud)

小智 2

您需要设置一个环境变量来告诉它不要使用内联脚本:

INLINE_RUNTIME_CHUNK=假

将其添加到您的 .env 文件中,当您重建时,React 的违规部分将被放入一个文件中。