From d7852834683a34b5a77acc698dbb15eefe09dcce Mon Sep 17 00:00:00 2001 From: "WIN-87ES3P38OPV\\EDY" Date: Tue, 28 Jul 2026 17:04:47 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E8=AE=BE=E7=BD=AE=E7=BC=93=E5=AD=98?= =?UTF-8?q?=E6=96=B9=E6=B3=95app.getCache\setCache?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.js | 38 ++++++++++++++++++++++++++++++++++++-- preload.js | 28 ++++++++++++++++++++++++++-- 2 files changed, 62 insertions(+), 4 deletions(-) diff --git a/main.js b/main.js index c5902b8..637d7c7 100644 --- a/main.js +++ b/main.js @@ -2,13 +2,33 @@ * @Author: 李皓 hao_li_work@163.com * @Date: 2026-07-28 15:22:20 * @LastEditors: 李皓 hao_li_work@163.com - * @LastEditTime: 2026-07-28 16:25:17 + * @LastEditTime: 2026-07-28 16:59:56 * @FilePath: \pc\main.js * @Description: * @Version: 1.0.0 */ -const { app, BrowserWindow } = require('electron') +const { app, BrowserWindow, ipcMain } = require('electron') const path = require('path') +const fs = require('fs') + +// 缓存文件路径(存储在应用用户数据目录下) +const cacheFile = path.join(app.getPath('userData'), 'app-cache.json') + +// 读取缓存文件 +function readCache() { + try { + if (fs.existsSync(cacheFile)) { + const raw = fs.readFileSync(cacheFile, 'utf-8') + return JSON.parse(raw) + } + } catch { /* 忽略解析错误 */ } + return {} +} + +// 写入缓存文件 +function writeCache(data) { + fs.writeFileSync(cacheFile, JSON.stringify(data, null, 2), 'utf-8') +} const createWindow = () => { const win = new BrowserWindow({ @@ -26,5 +46,19 @@ const createWindow = () => { } app.whenReady().then(() => { + // 注册 IPC 处理器:获取缓存 + ipcMain.handle('get-cache', (_event, key) => { + const cache = readCache() + return key ? cache[key] : cache + }) + + // 注册 IPC 处理器:设置缓存 + ipcMain.handle('set-cache', (_event, key, value) => { + const cache = readCache() + cache[key] = value + writeCache(cache) + return true + }) + createWindow() }) \ No newline at end of file diff --git a/preload.js b/preload.js index fc0e487..e24cc4f 100644 --- a/preload.js +++ b/preload.js @@ -7,7 +7,7 @@ * @Description: * @Version: 1.0.0 */ -const { contextBridge } = require('electron') +const { contextBridge, ipcRenderer } = require('electron') const nodeNet = require('net') const dns = require('dns') @@ -62,6 +62,30 @@ const appSensor = { name: 'appSensor' } -// 安全暴露 API 给渲染进程(挂载到 window.net,页面中可用 net.ping() 调用) +/** + * 应用缓存对象(数据持久化到本地文件) + */ +const app = { + /** + * 获取缓存数据 + * @param {string} key - 缓存键名 + * @returns {Promise} 缓存值 + */ + getCache(key) { + return ipcRenderer.invoke('get-cache', key) + }, + /** + * 设置缓存数据 + * @param {string} key - 缓存键名 + * @param {any} value - 缓存值(建议传入 JSON.stringify 后的字符串) + * @returns {Promise} + */ + setCache(key, value) { + return ipcRenderer.invoke('set-cache', key, value) + } +} + +// 安全暴露 API 给渲染进程 contextBridge.exposeInMainWorld('net', networkUtil) contextBridge.exposeInMainWorld('appSensor', appSensor) +contextBridge.exposeInMainWorld('app', app)