关于create-react-app:createreactapp脚手架搭建chrome插件项目

36次阅读

共计 3106 个字符,预计需要花费 8 分钟才能阅读完成。

背景

上篇文章《前端我的项目本地调试计划》中讲到开发 chrome 拓展插件帮忙实现 Cookie 复制,从而实现本地我的项目调试。但插件采纳的是原生 JS 开发的,本文来探讨如何在我的项目中引入 React?

我的项目实际

首先,执行上面命令初始化我的项目

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

创立的我的项目构造如下:

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

批改 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 目录寄存图标:

在 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;

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

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

应用插件后发现报了如下谬误

谬误的起因是内容安全策略不容许在 index.html 中应用内联脚本

webpack 能够设置不容许注入内联脚本,能够在根目录下创立.env 文件,其中增加 INLINE_RUNTIME_CHUNK=false,该字段示意是否容许注入内联脚本;或者还能够装置 cross-env,更改 build 命令,两种形式都能够用来设置环境变量。

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

而后从新 build,测试插件性能胜利!

正文完
 0