preload-script.md
1 # Preload Script 2 3 The preload script in Electron.js is a secure area designed for communication between the main and renderer processes. It is typically used for **[IPC communication](https://www.electronjs.org/docs/latest/tutorial/ipc)**. 4 5 For more information, see the following articles https://www.electronjs.org/docs/latest/tutorial/tutorial-preload 6 7 For compatibility and security with the latest version of Electron, we do not recommend using the old `electron/remote` module. If you want to utilize system events or Node scripts, it is recommended to do so in the main process, not the renderer. 8 9 TUUI's preload script is located in the `src/preload` folder. To create a new IPC communication channel, add the channel name to the following variable to whitelist it for communication. 10 11 - `mainAvailChannels`: Send an event from main to renderer. (`window.mainApi.send('channelName')`) 12 - `rendererAvailChannels`: Send an event from renderer to main. (`mainWindow.webContents.send('channelName')`) 13 14 When sending events from renderer to main, you access the `window.mainApi` object instead of `ipcRenderer.send`. The `mainApi` is a placeholder name provided in the template for demonstration purposes only. It should not be used in production implementations. For actual integrations like **MCP servers**, use the dedicated `mcpServers` API instead. 15 16 Here are the supported functions for mainApi: 17 18 - `send`: Send an event to main. 19 - `on`: A listener to receive events sent by main. 20 - `once`: A listener to receive events sent by main. (Handle only one call) 21 - `off`: Remove an event listener 22 - `invoke`: Functions that can send events to main and receive data asynchronously. 23 24 To change and modify `mainApi`, you need to modify `exposeInMainWorld` in `src/preload/index.ts`.