Create react app scaffolding chrome plug-in project

Time:2021-10-14

background

The previous article “local debugging scheme of front-end project” talked about developmentchromeExtension plug-in help completeCookieCopy to achieve local project debugging. But the plug-in is nativeJSDevelopment, this paper discusses how to introduce in the projectReact

Project practice

First, execute the following command to initialize the project

create-react-app chrome-extension --template typescript

The project structure created is as follows:

Create react app scaffolding chrome plug-in project

Delete the files circled in red and adjust the structure as follows:

Create react app scaffolding chrome plug-in project

modifypubicFoldermanifest.jsonAdd icons and permissions to be used in the configuration file. The overall configuration is as follows:

{
  "Manifest_version": 2, // when it is 2, the content security policy is enabled by default
  "name": "debug",
  "Description": "front end project debugging tool",
  "version": "1.0.0",
  "icons": {
    "16": "/images/icon16.png",
    "32": "/images/icon32.png",
    "48": "/images/icon48.png",
    "128": "/images/icon128.png"
  },
  "permissions": [
    "cookies",
    "tabs",
    "http://*/*",
    "https://*/*",
    "storage"
  ],
  "browser_action": {
    "default_icon": {
      "16": "/images/icon16.png",
      "32": "/images/icon32.png",
      "48": "/images/icon48.png",
      "128": "/images/icon128.png"
    },
    "Default_popup": "index. HTML" // a pop-up page appears
  },
  "Content_security_policy": "script SRC 'self'; object SRC 'self'" // content security policy (CSP)
}

deleteindex.htmlThe reference of the file in the is adjusted as follows:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

staypublicAdd inimagesDirectory storage Icon:

Create react app scaffolding chrome plug-in project

stayApp.tsxrealizationCookieCopy function, I introduced it hereantdComponent library

import React from 'react';
import styles from './App.module.css';
import { Button, Form, Input } from 'antd';
declare const chrome: any;

interface ICookie {
  name: string;
  value: string;
  path: string;
  secure: string
  domain: string;
  hostOnly: boolean;
  httpOnly: boolean;
  expirationDate: number;
  storeId: string;
  session: boolean;
}

interface ITab {
  id:number;
  index:number;
  windowId:number;
  selected:boolean;
  pinned:boolean;
  url:string;
  title:string;
  favIconUrl:string;
  status:string;
  incognito:boolean;
}

function App() {

  const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };

  /**Redirect*/
  const redirectTo = (url: string) => {
    window.open(url);
  }

  /**Get address bar*/
  const getUrl = (): Promise<ITab> => {
    return new Promise((resolve) => {
      chrome.tabs.getSelected(null, resolve)
    })
  }

  /**Get cookie*/
  const getCookie = (url: string): Promise<ICookie[]> => {
    return new Promise(async (resolve) => {
      chrome.cookies.getAll({ url }, resolve)
    })
  }

  /**Set cookies*/
  const setCookie = (cookies: ICookie[], redirect_url: string) => {
    return new Promise<void>(async (resolve) => {
      cookies.forEach((cookie) => {
        const { name, value, path, secure, expirationDate, storeId } = cookie;
        chrome.cookies.set({ url: redirect_url, name, value, path, secure, expirationDate, storeId, domain: 'localhost' });
      })
      resolve();
    })
  }

  /**Callback after form validation passes*/
  const onFinish = async (values: any) => {
    const { url } = values;
    if (!url) alert('Please input your debug url!');
    const tab = await getUrl();
    const cookies = await getCookie(tab.url);
    setCookie(cookies, url).then(() => redirectTo(url));
  }

  return (
    <div className={styles.container}>
      <Form
        {...layout}
        name="basic"
        onFinish={onFinish}
        className={styles.form}
      >
        <Form.Item
          Label = "debug address"
          name="url"
          rules={[{ pattern: /^https?:\/\/*\/*/, message: 'Please input your validable url!' }]}
        >
          <Input placeholder="Please input your debug url!" />
        </Form.Item>

        <Form.Item>
          < button type = "primary" htmltype = "submit" > debugging < / button >
        </Form.Item>
      </Form>
    </div>
  );
}

export default App;

When performing a build,publicThe files in are copied directly to the build output folderbuildThe pop-up script will also be injected into the database after compilation and compressionindex.html

Create react app scaffolding chrome plug-in project

Create react app scaffolding chrome plug-in project

takebuildAdd the directory to the expansion of Google browser

Create react app scaffolding chrome plug-in project

After using the plug-in, the following errors are found

Create react app scaffolding chrome plug-in project

The reason for the error isContent security policy does not allowindex.htmlUsing inline scripts in

Create react app scaffolding chrome plug-in project

webpackYou can set that inline script injection is not allowed and can be created in the root directory.envFile to set environment variables whereINLINE_RUNTIME_CHUNK=false, this field indicates whether inline script injection is allowed; Or you can installcross-env, changebuildCommand:

"build": "cross-env INLINE_RUNTIME_CHUNK=false react-scripts build",

Then rebuild, test plug-in function succeeded!