背景

上篇文章《前端项目本地调试方案》中讲到开发chrome拓展插件帮助完成Cookie复制,从而实现本地项目调试。但插件采用的是原生JS开发,本文来探讨如何使用creact-react-app搭建chrome插件应用?

项目实践

初始化目录结构

首先,执行下面命令初始化项目

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

创建的项目结构如下:

image.png

将红色圈出的文件删除,调整的结构如下:

image.png

修改pubic文件夹中manifest.json配置文件,添加需要使用的图标、权限,整体配置如下:

{
  "manifest_version": 2, // 为2时默认开启内容安全策略
  "name": "debug",
  "description": "前端项目调试工具",
  "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" // 弹窗页面
  },
  "content_security_policy": "script-src 'self'; object-src 'self'" // 内容安全策略(CSP)
}

删除index.html中文件的引用,调整后如下:

<!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>

public中添加images目录存放图标:

image.png

Cookie复制逻辑

App.tsx实现Cookie复制功能,这里我引入了antd组件库

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 },
  };

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

  /** 获取地址栏 */
  const getUrl = (): Promise<ITab> => {
    return new Promise((resolve) => {
      chrome.tabs.getSelected(null, resolve)
    })
  }

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

  /** 设置Cookie */
  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();
    })
  }

  /** 表单验证通过后的回调 */
  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="调试地址"
          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">调试</Button>
        </Form.Item>
      </Form>
    </div>
  );
}

export default App;

添加chrome全局变量

由于要使用chromeAPI,而chrome没有定义,使用时会报TS类型错误。在react-app-env.d.ts中添加

declare var chrome: any;

构建

执行构建时,public中的文件会直接复制到构建输出文件夹build中,而弹窗的脚本也会在编译压缩后注入到index.html

image.png

image.png

build目录添加到谷歌浏览器的拓展中

image.png

内容安全策略

使用插件后发现报了如下错误

image.png

错误的原因是内容安全策略不允许在index.html中使用内联脚本

image.png

webpack可以设置不允许注入内联脚本,可以在根目录下创建.env文件设置环境变量,其中添加INLINE_RUNTIME_CHUNK=false,该字段表示是否允许注入内联脚本;或者还可以安装cross-env,更改build命令,然后重新build

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

记得要微笑
1.9k 声望4.5k 粉丝

知不足而奋进,望远山而前行,卯足劲,不减热爱。