自己搭架子确实不会,好在github上有已经搭好的架子,具体见:https://github.com/lxieyang/chrome-extension-boilerplate-react
项目是基于react1、scss、webpack5搭建的chrome v3版本的,很全面。可以直接下载官方文件,也可以下载我简单整理后的文件:https://gitee.com/idonotyou/react-chrome-extension
与我们开发密切相关的就是src目录,基本上按照固定的目录开发是不会出问题的。


-manifest,配置文件。在manifest.json中指定文件时可以直接写文件名即可,应该是在打包时将文件地址给处理好了
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*", "" ],
"js": ["contentScript.bundle.js"],
"css": ["content.styles.css"]
}
],
"devtools_page": "devtools.html",
"web_accessible_resources": [
{
"resources": ["content.styles.css", "icon-128.png", "icon-34.png"],
"matches": []
}
]
下载依赖
npm install
运行
npm run start
会生成一个build文件夹,在浏览器扩展里将该文件导入,后面就可以实现热更新
打包
npm run build
popup

这里向说一下脚本注入,上面提到的content目录是存放直接注入到页面的脚本。但是有时候想要点击按钮后在往页面里进行脚本注入,这时可以采用下面这种写法
// popup.jsx
import React from 'react';
import logo from '../../assets/img/logo.svg';
import './Popup.css';
import Greetings from '../../containers/Greetings/Greetings'
import { Button } from 'antd';
import { funaa } from './handle';
const Popup = () => {
// 注入脚本
const insertScripts = () => {
chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
let tab = tabs.length ? tabs[0] : null;
if (tab) {
if (/^(http(s)?|file):\/\//.test(tab.url)) {
//依赖注入
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: funaa
});
}
}
});
}
return (
<div className="App">
<p>这里是popup弹窗页</p>
<img className='App-logo' src={logo} alt="图片" />
<Greetings />
<Button type='primary' onClick={insertScripts}>按钮</Button>
</div>
);
};
export default Popup;
// handle.js
export const funaa = () => {
console.log(123)
}
最开始的想法是直接往页面里注入handle.js文件的,但是提示文件找不到,后来就改为上面的注入方法
NewTab

Options


Panel

水平有限,遇到问题可以查看官方 Issues,或者百度查找答案
manifest.json文件的name属性后 ,扩展无法正常发起通知。百度查到的原因:Chrome浏览器缓存了旧的插件信息,导致无法正常发起通知。删除插件然后重新加载可以解决