最近使用uni-app开发Chrome遭遇了一些问题,我都一一暂时解决了我的需求
1.我所指的编译是这个编译
image.png
2.Chrome插件的根目录必要文件是给Chrome的manifest.json文件,这个文件不要和uni-app项目的manifest.json文件搞混了
3.Chrome插件的弹出Popup气泡窗口的html文件中一定不能包含JavaScript具体代码,但是uni-app编译后的文件的index.html第一个script标签中包含了一些初始化的代码
4.每次uni-app编译后,需手动放入manifest.json文件和将index.html中的初始化代码文件化,这看起来过于麻烦
5.我用一个node实例自动实现4中需要实现的操作,大概思路是监听h5文件夹被重新创建后执行index.html文件的修改,以及写入一个manifest.json和一个insert.js文件,这个insert.js文件是index.html中的初始化代码转过来的,index.html中的初始化被替换成了js文件引入
6.下面是我的nodejs文件的代码,uni-app编译之前用node启动它,然后一直挂着,请注意,需将文件夹目录变量替换成自己的目录,在第5行,路径一定是以build文件夹结尾
const fs = require('fs');
const path = require('path');
// 指定要监听的文件夹路径和文件夹名
const folderPath = 'D:/resource/Document/HBuilderProjects/PrivateFavorites_/unpackage/dist/build';
const folderName = 'h5';
function extractScriptContent(str) {
const regex = /<script\b[^>]*>([\s\S]*?)<\/script>/i;
const match = str.match(regex);
if (match && match[1]) {
return match[1];
}
return '';
}
// 设置监听器
fs.watch(folderPath, (eventType, filename) => {
if (eventType === 'rename' && filename === folderName) {
const folderFullPath = path.join(folderPath, folderName);
const filePath = path.join(folderFullPath, 'index.html');
try {
fs.accessSync(filePath, fs.constants.F_OK);
const fileContent = fs.readFileSync(filePath, 'utf-8');
let script_ = fileContent.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)[0]
let newHtml = fileContent.replace(script_, '<script src="./assets/insert.js"></script>')
let rootPath = folderPath + '/' + folderName
fs.writeFileSync(rootPath + '/index.html', newHtml)
let manifestContent = {
"manifest_version": 3,
"name": "PrivateFavorites",
"version": "0.1.1",
"description": "A Chrome Extension of a Favorite with Privacy Protection Capability",
"icons": {
"16": "/static/image/icon.png",
"48": "/static/image/icon.png",
"128": "/static/image/icon.png"
},
"permissions": [
"storage",
"contextMenus",
"activeTab",
"tabs",
"bookmarks",
"commands",
"history"
],
"action": {
"default_popup": "index.html",
"default_icon": {
"16": "/static/image/icon.png",
"48": "/static/image/icon.png",
"128": "/static/image/icon.png"
}
},
"commands": {
"_execute_action": {
"suggested_key": {
"default": "Ctrl+Shift+X",
"mac": "MacCtrl+Shift+X"
}
}
},
"options_ui": {
"page": "index.html#/pages/options/options",
"open_in_tab": true
}
}
fs.writeFileSync(rootPath + '/manifest.json', JSON.stringify(manifestContent));
fs.writeFileSync(rootPath + '/assets/insert.js', script_.replace('<script>', '').replace('</script>', ''));
console.error('编译成功');
} catch (err) {
console.error('编译中');
}
}
});