序幕:被GFW狙擊的第一次構建
當我在工位上輸入npm install electron
時,控制臺跳出的紅色警報如同數字柏林墻上的一道彈痕:
Error: connect ETIMEDOUT 104.20.22.46:443
網絡問題不用愁,請移步我的另外文章進行配置:
electron 客戶端 windows linux(麒麟V10)多系統離線打包 最新版 <一>_electron linux 離線打包-CSDN博客
第一章:構建electron-builder
builder排除文件夾,簡單配置如下(package.json中):
"build": {"appId": "com.example.win7app","win": {"target": "nsis","defaultArch": "ia32"},"extraFiles": [{"from": "resources","to": "Resources","filter": ["**/*"]}],"nsis": {"oneClick": false,"allowToChangeInstallationDirectory": true}},
我們需要在這個文件夾中讀取dll文件,同時希望它打包后在安裝目錄下。
第二章:跨維度通信協議——主進程與渲染進程的量子糾纏
根目錄添加preload.js,添加如下代碼:
// preload.js
const { contextBridge, ipcRenderer } = require('electron');// 向渲染進程暴露安全的 API 方法
contextBridge.exposeInMainWorld('electronAPI',{// 示例:調用 Node.js 文件系統 APIreadFile: async (path) => {const fs = await import('fs/promises');return fs.readFile(path, 'utf-8');},// 示例:進程間通信(IPC)openDialog: () => ipcRenderer.invoke('dialog:open'),// 檢查是否存在加密狗并且是否匹配成功checkIfLock: () => ipcRenderer.invoke('checkIfLock'),captureUKey: () => ipcRenderer.invoke('captureUKey'),// 關閉窗口closeWindow: () => ipcRenderer.invoke('closeWindow'),// 監聽打開設置onAction: (callback) => {ipcRenderer.on('renderer-action', (event, arg) => callback(arg))},}
)
然后再mainjs(electron主進程)中配置文件:
let mainWindow, tray = null;
function createWindow() {mainWindow = new BrowserWindow({width: 800,height: 600,webPreferences: {preload: path.join(__dirname, 'preload.js'), // 指定預加載腳本contextIsolation: true, // 開啟上下文隔離(安全必備)nodeIntegration: false // 禁用直接 Node.js 訪問}})// 隱藏菜單mainWindow.setMenu(null);// 加載本地頁面(開發時可替換為本地服務地址,如 http://localhost:3000)mainWindow.loadFile(path.join(__dirname, 'src', 'index.html'));// 窗口關閉事件處理mainWindow.on('close', (event) => {if (!app.isQuiting) {event.preventDefault()const choice = dialog.showMessageBoxSync(mainWindow, {type: 'question',buttons: ['直接退出', '最小化到托盤'],title: '確認',message: '您要如何操作?',defaultId: 1})if (choice === 0) {app.isQuiting = trueapp.quit()} else {mainWindow.hide()}}})
}
最后在html中使用上述方法(html中使用):
<script>//【IPC通信】檢測開關(true false)
const checkIfLock = window.electronAPI.checkIfLock;
const checkArm = window.electronAPI.captureUKey;
const closeWindow = window.electronAPI.closeWindow;
// 打開設置
window.electronAPI.onAction(({ type, data }) => {switch(type) {case 'openSettings':showSetting()break;}
})// 顯示設置
function showSetting () {try {var remortroot = localStorage.dpm_root;var remortport = localStorage.dpm_port;if (remortroot != null) {$("#remortroot").val(remortroot);}if (remortport != null) {$("#remortport").val(remortport);}$('#myModal').modal('show');} catch (err) {$('#myModal').modal('show');}
}// ===========================================
var timeout;
var lockState = false;
$(function () {checkIfLock().then(res => {lockState = res;})//初始化設置var remortroot = localStorage.dpm_root;//服務器IP地址var remortport = localStorage.dpm_port;//端口號if (remortroot == null || remortroot == "" || remortroot == "undefined"|| remortroot == null || remortroot == "" || remortroot == "undefined") {var err = "首次登錄,請填寫網絡配置";showConfirmMsg(err, function (r) {if (r) {$('#myModal').modal('show');}});} else {loadLoginPage(remortroot, remortport);}
});function isPort(str) {var parten = /^(\d)+$/g;if (parten.test(str) && parseInt(str) <= 65535 && parseInt(str) >= 0) {return true;} else {return false;}
}
function isIP(strIP) {var re = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/gif (re.test(strIP)) {if (RegExp.$1 < 256 && RegExp.$2 < 256 && RegExp.$3 < 256 && RegExp.$4 < 256) return true;}return false;
}
function sendUrlPort(remortroot, remortport) {var err = "";if (isIP(remortroot)) {} else {err += "服務器地址無效,";}if (isPort(remortport)) {} else {err += "端口號無效,";}if (err != "" && err.length > 0) {err = err.substring(0, err.length - 1);showConfirmMsg(err, function (r) {if (r) {$('#myModal').modal('show');}});} else {layer.msg('正在加載登錄頁面,請稍候。。。', {icon: 16,shade: 0.01,time: 5000000,shadeClose: false});var dpmHid = $("#eam_hid").text();var ifUd = "";if (false == lockState) {//false代表 u盾登錄 需要驗證uidifUd = "xxx"}var url = "https://" + remortroot + ":" + remortport$.ajax({url: url,type: 'GET',timeout: 100000,datatype: "json",complete: function (response, textStatus) {//啟動u盾檢測timeout = setInterval("testUd()", 3000);layer.closeAll();if (response.status == 200) {localStorage.dpm_root = remortroot;localStorage.dpm_port = remortport;$('#github-iframe').attr('src', url);} else if (textStatus == 'timeout') {showConfirmMsg('未能成功連接系統(超時),請檢查網絡配置或聯系管理員!', function (r) {if (r) {$('#myModal').modal('show');}});} else {showConfirmMsg('未能成功連接系統,請檢查網絡配置或聯系管理員!', function (r) {if (r) {$('#myModal').modal('show');}});}}});}
}//啟動時:加載登錄頁,并判斷u端是否存在
function loadLoginPage(remortroot, remortport) {checkArm().then(res => {if (true == lockState) {if (false == res.flag) {$("#eam_hid").text("");}sendUrlPort(remortroot, remortport);} else {if (true == res.flag) {$("#eam_hid").text(res.randomNum);sendUrlPort(remortroot, remortport);} else {showLongErrorMsg("未插入U盾");}}})}
//啟動后 監測u盾是否插入,未插入則退出系統
function testUd() {checkArm().then(res => {if (true == lockState) {if (false == res) {$("#eam_hid").text("");}} else {if (false == res) {clearInterval(timeout);showLongErrorMsg("未插入U盾");}}})
}
function showConfirmMsg(msg, callBack) {art.dialog({id: 'confirmId',title: '系統提示',content: msg,icon: 'warning',background: '#000000',opacity: 0.1,lock: true,button: [{name: '確定',callback: function () {callBack(true);},focus: true}]});
}
//錯誤提示
function showErrorMsg(msg) {top.art.dialog({id: 'errorId',title: '系統提示',content: msg,icon: 'error',time: 5,background: '#000',opacity: 0.1,lock: true,okVal: '關閉',ok: true});
}
function showLongErrorMsg(msg) {top.art.dialog({id: 'errorId',title: '5秒后自動關閉客戶端...',content: msg,icon: 'error',time: 5,background: '#000',opacity: 0.1,lock: true,cancelVal: '關閉',cancel: function () {closeWindow();},close: function () {closeWindow();}});
}//彈出框事件
$("#initsetbtn").click(function () {var remortroot = $("#remortroot").val();var remortport = $("#remortport").val();$('#myModal').modal('hide');loadLoginPage(remortroot, remortport);
});</script>
第三章:調用dll
調用dll推薦使用koffi。另一篇文章也有說明:
Electron馴龍記:在Win7的廢墟上喚醒32位DLL古老巨龍-CSDN博客
示例代碼:
?
// 在mainjs中// 是否捕獲U盾
ipcMain.handle('captureUKey', () => {return new Promise((resolve, reject) => {let promiseAry = [];var count = 0;while (count++ < 20) { //連續20次都失敗 才認為失敗promiseAry.push(checkOnceUKey());}Promise.all(promiseAry).then((results) => {console.log('所有檢查結果:', results);if (Array.isArray(results) && results.length > 0) {resolve({flag: results.filter(item => item.flag == false).length == 0 ? true: false,randomNum: results[results.length - 1].randomNum || ''})} else {resolve({flag: false,randomNum: ''})}}) }).catch(error => {console.error('是否捕獲U盾出錯:', error);return false; // 讀取失敗})
})
// 單次檢查U盾
function checkOnceUKey() {return new Promise((resolve, reject) => {let flag = false;let randomNum = ''; // 隨機數// 常量定義const DONGLE_SUCCESS = 0;const koffi = require('koffi');// 加載 DLLconst dllPath = path.join(getDataPath(), 'Dongle_d.dll');const dongleLib = koffi.load(dllPath);// 定義結構體字段偏移量(單位:字節)const InfoStructOffsets = {m_Ver: 0,m_Type: 2,m_BirthDay: 4,m_Agent: 12,m_PID: 16,m_UserID: 20,m_HID: 24,m_IsMother: 32,m_DevType: 36};const InfoStructSize = 40;const Dongle_Enum = dongleLib.func('int Dongle_Enum(void*, int*)');const Dongle_Open = dongleLib.func('int Dongle_Open(int*, int)');const Dongle_ResetState = dongleLib.func('int Dongle_ResetState(int)');const Dongle_GenRandom = dongleLib.func('int Dongle_GenRandom(int, int, void*)');const Dongle_Close = dongleLib.func('int Dongle_Close(int)');// 初始化緩沖區const dongleInfo = Buffer.alloc(1024); // 假設最多 25 個設備(1024 / 40 ≈ 25)const countBuffer = Buffer.alloc(4);countBuffer.writeInt32LE(0, 0);// 1?? 枚舉設備let result = Dongle_Enum(dongleInfo, countBuffer);console.log(`** Dongle_Enum **: 0x${result.toString(16).padStart(8, '0')}`);if (result !== DONGLE_SUCCESS) {console.error(`** Enum errcode **: 0x${result.toString(16).padStart(8, '0')}`);flag = false;}const deviceCount = countBuffer.readInt32LE(0);console.log(`** Find Device **: ${deviceCount}`);if (deviceCount === 0) {console.log('** No Device **');flag = false;}// 3?? 打開設備const handleBuffer = Buffer.alloc(4);result = Dongle_Open(handleBuffer, 0);const handle = handleBuffer.readInt32LE(0);console.log(`** Dongle_Open **: 0x${result.toString(16).padStart(8, '0')}`);if (result !== DONGLE_SUCCESS) {console.error(`** Open Failed **`);flag = false;} else {console.log(`** Open Success **: [handle=0x${handle.toString(16).padStart(8, '0')}]`);randomNum = `0x${handle.toString(16).padStart(8, '0')}`;Dongle_Close(handle);flag = true;}// 4?? 重置 COS 狀態/*result = Dongle_ResetState(handle);console.log(`Dongle_ResetState 返回值: 0x${result.toString(16).padStart(8, '0')}`);if (result !== DONGLE_SUCCESS) {console.error(`重置 COS 狀態失敗`);Dongle_Close(handle);return;}console.log('重置 COS 狀態成功');*/// 5?? 生成隨機數// const randomLen = 16;// const randomBuffer = Buffer.alloc(randomLen);// result = Dongle_GenRandom(handle, randomLen, randomBuffer);// console.log(`Dongle_GenRandom : 0x${result.toString(16).padStart(8, '0')}`);// if (result !== DONGLE_SUCCESS) {// console.error(`生成隨機數失敗`);// Dongle_Close(handle);// } else {// randomNum = randomBuffer.toJSON().data.map(b => PrefixZero(b, 2)).join(' ').toUpperCase();// Dongle_Close(handle);// }//console.log(`隨機數據: ${randomBuffer.toJSON().data.map(b => PrefixZero(b, 2)).join(' ').toUpperCase()}`);/*// 6?? 關閉設備result = Dongle_Close(handle);console.log(`Dongle_Close 返回值: 0x${result.toString(16).padStart(8, '0')}`);if (result !== DONGLE_SUCCESS) {console.error(`關閉設備失敗`);return;}console.log('成功關閉設備');*/resolve({flag,randomNum})}).catch(err => {console.error('單次讀取U盾失敗:', err);return false; // 讀取失敗})
}
后記:與時間賽跑的混亂代碼之旅?
回首這次Electron的改造征程,更像是一場與編譯警告共舞的午夜狂奔。由于項目周期緊張,某些技術方案難免帶著「先跑起來再優化」的倉促痕跡——就像在暴雨中搭建帳篷,難免會有幾處漏水的接縫。
過程中那些臨時添加的Webpack補丁、為繞過環境問題硬編碼的路徑、甚至為了緊急交付保留的TODO
注釋,都如同代碼迷宮中未清理的記號。雖然最終功能得以實現,但我深知這座代碼大廈的某些承重墻上,或許還留著需要加固的裂縫。
在此特別懇請各位同行:若您在閱讀中發現任何邏輯漏洞、安全隱患或架構缺陷,請務必通過Issue或郵件指正。您的一條建議,或許就能避免某個深夜的生產環境告警。技術之路本就如履薄冰,唯有開放交流才能讓我們的每一步走得更穩。
~ end