Electron ^30.0.3+ReactJS在Mac M1上ipcRenderer失效求助
Mac M1上Electron的ipcRenderer不工作问题解决
先澄清:你看到的Autofill报错是DevTools内部问题
[65486:0513/222624.486948:ERROR:CONSOLE(1)] "Request Autofill.enable failed. {"code":-32601,"message":"'Autofill.enable' wasn't found"}", source: devtools://devtools/bundled/core/protocol_client/protocol_client.js (1)
这个报错是Chrome DevTools的自身问题,和你的ipcRenderer功能无关,不会影响应用逻辑,可以忽略。如果介意,可尝试更新Electron到最新稳定版,或暂时关闭DevTools。
导致ipcRenderer不工作的真正原因及修复
1. 修正webPreferences配置冲突
当开启contextIsolation: true时,nodeIntegration: true是多余且冲突的(contextIsolation开启后,渲染进程无法直接访问Node.js API),应该移除nodeIntegration: true配置(默认就是false)。
2. 调整electron-reload加载时机
electron-reload的加载位置不对,可能导致预加载脚本没有被正确重载。需要把它移到app.whenReady()的回调中,确保在应用初始化后加载。
3. 确认渲染进程调用API的方式
确保你在index.html中是通过暴露的全局对象调用API,示例:
<script> // 点击按钮触发通知 document.querySelector('#notifyBtn').addEventListener('click', () => { window.electron.notificationApi.sendNotification('测试通知内容'); }); </script>
修正后的完整代码
main.js
const { BrowserWindow, app, ipcMain, Notification } = require('electron'); const path = require('path'); function createWindow() { const win = new BrowserWindow({ width: 1200, height: 800, backgroundColor: "white", webPreferences: { preload: path.join(__dirname, 'preload.js'), worldSafeExecuteJavaScript: true, contextIsolation: true } }) win.loadFile('index.html'); win.webContents.openDevTools(); } app.whenReady().then(() => { require('electron-reload')(__dirname, { electron: path.join(__dirname, 'node_modules', '.bin', 'electron') }) createWindow() }) ipcMain.on('notify', (_, message) => { new Notification({title: 'Notification', body: message}).show(); }) // 适配Mac应用生命周期 app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit() }) app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow() })
preload.js(无需修改)
const { ipcRenderer, contextBridge } = require('electron'); contextBridge.exposeInMainWorld('electron', { notificationApi: { sendNotification(message) { ipcRenderer.send('notify', message); } } })
内容的提问来源于stack exchange,提问作者shazim ali
相关产品推荐
相关产品推荐

