浏览代码

fix: 修复 Electron 环境下日志不生成的问题 (src/log/logger.js)

- 更新 isElectron() 检测逻辑,使用 window.electronAPI 替代 window.require
- 修复因 contextIsolation 导致无法访问 ipcRenderer 的问题
- 使用 preload.js 暴露的安全 API 进行日志写入
sw 1 周之前
父节点
当前提交
0b259a8610
共有 1 个文件被更改,包括 4 次插入9 次删除
  1. 4 9
      src/log/logger.js

+ 4 - 9
src/log/logger.js

@@ -1,16 +1,11 @@
 const isElectron = () =>
   typeof window !== 'undefined' &&
-  window.require &&
-  window.require('electron')?.ipcRenderer;
+  window.electronAPI &&
+  typeof window.electronAPI.writeLog === 'function';
 
 // 检测是否在 Cypress 测试环境中
 const isTestEnvironment = () =>
   typeof window !== 'undefined' && window.Cypress;
-
-let ipcRenderer = null;
-if (isElectron()) {
-  try { ipcRenderer = window.require('electron').ipcRenderer; } catch {}
-}
 //避免obj是递归引用导致崩溃
 function safeStringify(obj) {
   const cache = new Set();
@@ -35,8 +30,8 @@ function proxyLog(level) {
       return;
     }
     
-    if (ipcRenderer) {                       // ② Electron 环境
-      ipcRenderer.invoke('write-log', level, msg).catch(() => {});
+    if (isElectron()) {                      // ② Electron 环境
+      window.electronAPI.writeLog(level, msg).catch(() => {});
     } else if (typeof fetch !== 'undefined') {
       // // ③ 纯 Web 或 pkg-static:发一条异步 POST /log,不阻塞、不报错
       // fetch('/log', {