📜  ipcrenderer preload.js - Javascript (1)

📅  最后修改于: 2023-12-03 15:31:26.544000             🧑  作者: Mango

IPCRenderer Preload.js - JavaScript

Introduction

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.

Usage
  1. Create a preload.js file, and add it to the 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')
})
  1. In the preload.js file, you can access the 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!')
  1. You can also use the 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))
})
Conclusion

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.