Electron/Node.js中如何从主进程向主窗口HTML传递回调数据
Let's fix this step by step—here's why your current setup isn't working, plus the code changes you need:
What's Going Wrong
- Main Process Timing Issue: You wrapped the
webContents.send()call inside adid-finish-loadlistener. This event only fires when the main window finishes loading for the first time. By the time you close the add window and try to send data, the main window has already loaded, so this listener never triggers—your message never gets sent. - Missing Listener in Main Window: Your main window's renderer script isn't set up to listen for the
item:receivedevent from the main process, so even if the message was sent, there's nothing to catch it.
1. Update Your Preload Script
First, add a method to safely expose event listening functionality to the main world. We'll wrap ipcRenderer.on so the renderer can listen for incoming data without full access to IPC:
contextBridge.exposeInMainWorld('windowControls', { add: (data) => ipcRenderer.send('item:add', data), // New method to listen for incoming items onItemReceived: (callback) => { ipcRenderer.on('item:received', (event, item) => { callback(item); }); } });
2. Fix the Main Process Code
Remove the unnecessary did-finish-load listener—since your main window is already open when the add window sends data, you can send the message directly:
// Catch item:add ipcMain.on('item:add', (e, item) => { console.log('item', item); // Send data immediately to the main window mainWindow.webContents.send('item:received', item); addWindow.close(); });
3. Set Up the Main Window's Renderer Script
In your rendererMain.js, use the exposed onItemReceived method to listen for data and update your UI. This listener stays active as long as the main window is open, so it'll catch every new item sent from the add window:
// Listen for incoming items from the main process window.windowControls.onItemReceived((item) => { console.log('Received item in main window:', item); // Example: Add the item to your UI const itemList = document.getElementById('itemList'); // Replace with your element ID const newItemElement = document.createElement('li'); newItemElement.textContent = item; itemList.appendChild(newItemElement); });
Why This Works
- The preload script maintains Electron's security boundaries while giving the renderer access to necessary IPC functionality.
- The main process sends data immediately after receiving it, no longer waiting for a load event that won't fire again.
- The main window's persistent listener ensures it catches the message every time the add window sends data, even after the initial page load.
内容的提问来源于stack exchange,提问作者Zeghra

