首页 > 解决方案 > 如何使用 React 组件覆盖 Chrome 新标签页内容

问题描述

我正在尝试创建一个 React 应用程序/Chrome 扩展程序,它会覆盖 Google Chrome 中新选项卡的内容。我已经使用create-react-app并且只是试图用内容覆盖新选项卡的App.js内容。文件夹结构直接来自最初的create-react-app,如下所示。

    build
    node_modules
    Public
      favicon.ico
      index.html
      logo192.png
      logo512.png
      manifest.json
    src
      App.css
      App.js
      app.test.js
      index.css
      index.js
      logo.svg
    ..
    ..

我的manifest.json文件看起来像这样。

    {
      "name": "..",
      "author": "..",
      "version": "1.0.1",
      "manifest_version": 2,
      "description": "..",
      "chrome_url_overrides": {
        "newtab": "index.html"
      }
    }

这就是我的index.html样子。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>

我的index.js文件看起来像这样。

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

serviceWorker.unregister();

我尝试插入以下内容,但收到一个空白页面。

<script src="../src/index.js"></script>

我将如何覆盖新选项卡的内容App.js

标签: reactjsgoogle-chrome-extension

解决方案


最初我将我的manifest.json文件修改为以下内容。

{
  "name": "..",
  "author": "..",
  "version": "1.0.1",
  "manifest_version": 2,
  "description": "..",
  "chrome_url_overrides": {
    "newtab": "index.html"
  },
  "content_security_policy": "script-src 'self' 'YOUR HASH'; object-src 'self'"
}

YOUR HASH可以从控制台中找到,如下所示

来自控制台的高亮哈希

但是,我选择了另一种方法。我.env在根目录中创建了一个文件并将以下内容放入其中

INLINE_RUNTIME_CHUNK=false

推荐阅读