背景:
一直想开发一个chrome插件,但是找不到合适的IDE,早年间写过一个,还是用记事本写的,前段时间学了点uniapp开发,就想着用HBuilder来开发,是不是可以做出更炫酷的页面,但是HBuilder并没有chrome插件的项目类型,好在用vite可以需要做一些调整,就可以完美支持了。
纲领:
chrome插件官方文档:
https://developer.chrome.com/docs/extensions/develop?hl=zh-cn
任务:
为了适配Chrome的规范,需要对Hbuilder的编译功能做以下的配置:
1.编写manifest.json,定义插件的内容、权限等
2. 把chrome插件所需的manifest.json,logo,js等静态文件复制到根目录
3.把编译生成的html文件中的js代码移到单独的js文件中(chrome插件的html文件不能包含内嵌的javascript代码)
行动:
1. 在项目中创建一个文件夹,用于存放manifest.json和其他文件
2. 在manifest.json中,声明pupup为index.html(uniapp项目生成入口html的就是这个名字), logo文件路径等
{
"name": "Hello Extensions",
"description": "Base Level Extension",
"version": "1.0",
"manifest_version": 3,
"action": {
"default_popup": "index.html",
"default_icon": "images/hello_extensions.png"
}
}
manifest.json具体规范见:https://developer.chrome.com/docs/extensions/reference/manifest?hl=zh-cn
3. 配置vite
在项目根目录创建vite.config.js, 编写复制插件根目录文件和修改index.html的插件函数:
import path from 'path';
import fs from 'fs-extra';
import { defineConfig } from 'vite';
import uni from '@dcloudio/vite-plugin-uni';
function copyFile() {
return {
enforce: 'post',
async writeBundle() {
console.log('复制插件所需的文件');
await fs.copy(
path.resolve(__dirname, 'ext_root'),
process.env.UNI_OUTPUT_DIR
);
},
};
}
// 修改HTML,适配chrome插件的要求:把javascript代码从html转移到单独的js文件
function modifyIndexHtml() {
return {
name: 'modify-index-html', // 插件名称
enforce: 'post', // 确保在 HTML 处理之后执行
closeBundle() {
// 匹配<script>片段
const htmlFilePath = path.join(process.env.UNI_OUTPUT_DIR,'index.html');
const html = fs.readFileSync(htmlFilePath, 'utf-8');
let script_ = html.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)[0];
// 写入index.js
const jsFilePath = path.join(process.env.UNI_OUTPUT_DIR,'assets','index.js');
fs.writeFileSync(jsFilePath, script_.replace('<script>', '').replace('</script>', ''),'utf-8');
// 修改 html 字符串
let newHtml = html.replace(script_, '<script src="./assets/index.js"></script>');
fs.writeFileSync(htmlFilePath, newHtml,'utf-8');
}
}
}
export default defineConfig({
plugins: [
uni(),
copyFile(),
modifyIndexHtml(),
],
});
4.发行:
经过这一通操作, 在HBuilder上点【发行】-【网站-PC Web或手机...】就可以直接生成chrome插件的文件夹了。
5. 在浏览器加载插件
在浏览器进入chrome://extensions 或者 edge://extensions(我用的是Edge浏览器) ,点击【加载解压缩的扩展】,选中uniapp项目发布生成的web目录,就能加载刚才开发的插件了。
6. 测试
点击插件按钮,就能显示index.html的内容了
成果:
点击插件看看,有点小,哈哈哈