📅  最后修改于: 2023-12-03 15:31:26.544000             🧑  作者: Mango
In Electron, the ipcRenderer
module is used to communicate between the main process and the renderer process. Preload.js is a script that runs in the renderer process' context, which allows it to access ipcRenderer
and other Electron modules. This script can be used to provide additional functionalities to the renderer process's web page.
webPreferences
of your BrowserWindow instance when you create it.// main.js
const { app, BrowserWindow } = require('electron')
app.whenReady().then(() => {
const mainWindow = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
mainWindow.loadFile('index.html')
})
ipcRenderer
module and other Electron modules by using window.require
function.// preload.js
const { ipcRenderer } = window.require('electron')
ipcRenderer.send('message-from-renderer', 'Hello from Renderer process!')
contextBridge
module to expose the ipcRenderer
module to the renderer process's web page, this is strongly recommended for security reasons:// preload.js
const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('myAPI', {
sendMessage: (data) => ipcRenderer.send('message-from-renderer', data),
onMessageReceived: (func) => ipcRenderer.on('message-from-main', (event, data) => func(data))
})
ipcRenderer
Preload.js is a useful script for Electron developers to add extra functionalities to their renderer process. By using this script, you can communicate between the main process and renderer process easily, and provide more interaction between your web page and Electron.