Using Preload Scripts

Using Preload Scripts - 图1Follow along the tutorial

This is part 3 of the Electron tutorial.

  1. Prerequisites
  2. Building your First App
  3. Using Preload Scripts
  4. Adding Features
  5. Packaging Your Application
  6. Publishing and Updating

Learning goals

In this part of the tutorial, you will learn what a preload script is and how to use one to securely expose privileged APIs into the renderer process. You will also learn how to communicate between main and renderer processes with Electron’s inter-process communication (IPC) modules.

What is a preload script?

Electron’s main process is a Node.js environment that has full operating system access. On top of Electron modules, you can also access Node.js built-ins, as well as any packages installed via npm. On the other hand, renderer processes run web pages and do not run Node.js by default for security reasons.

To bridge Electron’s different process types together, we will need to use a special script called a preload.

Augmenting the renderer with a preload script

A BrowserWindow’s preload script runs in a context that has access to both the HTML DOM and a limited subset of Node.js and Electron APIs.

Using Preload Scripts - 图2Preload script sandboxing

From Electron 20 onwards, preload scripts are sandboxed by default and no longer have access to a full Node.js environment. Practically, this means that you have a polyfilled require function that only has access to a limited set of APIs.

Available APIDetails
Electron modulesRenderer process modules
Node.js modulesevents, timers, url
Polyfilled globalsBuffer, process, clearImmediate, setImmediate

For more information, check out the Process Sandboxing guide.

Preload scripts are injected before a web page loads in the renderer, similar to a Chrome extension’s content scripts. To add features to your renderer that require privileged access, you can define global objects through the contextBridge API.

To demonstrate this concept, you will create a preload script that exposes your app’s versions of Chrome, Node, and Electron into the renderer.

Add a new preload.js script that exposes selected properties of Electron’s process.versions object to the renderer process in a versions global variable.

preload.js

  1. const { contextBridge } = require('electron')
  2. contextBridge.exposeInMainWorld('versions', {
  3. node: () => process.versions.node,
  4. chrome: () => process.versions.chrome,
  5. electron: () => process.versions.electron
  6. // we can also expose variables, not just functions
  7. })

To attach this script to your renderer process, pass its path to the webPreferences.preload option in the BrowserWindow constructor:

main.js

  1. const { app, BrowserWindow } = require('electron')
  2. const path = require('node:path')
  3. const createWindow = () => {
  4. const win = new BrowserWindow({
  5. width: 800,
  6. height: 600,
  7. webPreferences: {
  8. preload: path.join(__dirname, 'preload.js')
  9. }
  10. })
  11. win.loadFile('index.html')
  12. }
  13. app.whenReady().then(() => {
  14. createWindow()
  15. })

Using Preload Scripts - 图3info

There are two Node.js concepts that are used here:

  • The __dirname string points to the path of the currently executing script (in this case, your project’s root folder).
  • The path.join API joins multiple path segments together, creating a combined path string that works across all platforms.

At this point, the renderer has access to the versions global, so let’s display that information in the window. This variable can be accessed via window.versions or simply versions. Create a renderer.js script that uses the document.getElementById DOM API to replace the displayed text for the HTML element with info as its id property.

renderer.js

  1. const information = document.getElementById('info')
  2. information.innerText = `This app is using Chrome (v${versions.chrome()}), Node.js (v${versions.node()}), and Electron (v${versions.electron()})`

Then, modify your index.html by adding a new element with info as its id property, and attach your renderer.js script:

index.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta
  6. http-equiv="Content-Security-Policy"
  7. content="default-src 'self'; script-src 'self'"
  8. />
  9. <meta
  10. http-equiv="X-Content-Security-Policy"
  11. content="default-src 'self'; script-src 'self'"
  12. />
  13. <title>Hello from Electron renderer!</title>
  14. </head>
  15. <body>
  16. <h1>Hello from Electron renderer!</h1>
  17. <p>👋</p>
  18. <p id="info"></p>
  19. </body>
  20. <script src="./renderer.js"></script>
  21. </html>

After following the above steps, your app should look something like this:

Electron app showing This app is using Chrome (v102.0.5005.63), Node.js (v16.14.2), and Electron (v19.0.3)

And the code should look like this:

docs/fiddles/tutorial-preload (27.0.1)Open in Fiddle

  • main.js
  • preload.js
  • index.html
  • renderer.js
  1. const { app, BrowserWindow } = require('electron')
  2. const path = require('node:path')
  3. const createWindow = () => {
  4. const win = new BrowserWindow({
  5. width: 800,
  6. height: 600,
  7. webPreferences: {
  8. preload: path.join(__dirname, 'preload.js')
  9. }
  10. })
  11. win.loadFile('index.html')
  12. }
  13. app.whenReady().then(() => {
  14. createWindow()
  15. app.on('activate', () => {
  16. if (BrowserWindow.getAllWindows().length === 0) {
  17. createWindow()
  18. }
  19. })
  20. })
  21. app.on('window-all-closed', () => {
  22. if (process.platform !== 'darwin') {
  23. app.quit()
  24. }
  25. })
  1. const { contextBridge } = require('electron')
  2. contextBridge.exposeInMainWorld('versions', {
  3. node: () => process.versions.node,
  4. chrome: () => process.versions.chrome,
  5. electron: () => process.versions.electron
  6. })
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta
  6. http-equiv="Content-Security-Policy"
  7. content="default-src 'self'; script-src 'self'"
  8. />
  9. <meta
  10. http-equiv="X-Content-Security-Policy"
  11. content="default-src 'self'; script-src 'self'"
  12. />
  13. <title>Hello from Electron renderer!</title>
  14. </head>
  15. <body>
  16. <h1>Hello from Electron renderer!</h1>
  17. <p>👋</p>
  18. <p id="info"></p>
  19. </body>
  20. <script src="./renderer.js"></script>
  21. </html>
  1. const information = document.getElementById('info')
  2. information.innerText = `This app is using Chrome (v${window.versions.chrome()}), Node.js (v${window.versions.node()}), and Electron (v${window.versions.electron()})`

Communicating between processes

As we have mentioned above, Electron’s main and renderer process have distinct responsibilities and are not interchangeable. This means it is not possible to access the Node.js APIs directly from the renderer process, nor the HTML Document Object Model (DOM) from the main process.

The solution for this problem is to use Electron’s ipcMain and ipcRenderer modules for inter-process communication (IPC). To send a message from your web page to the main process, you can set up a main process handler with ipcMain.handle and then expose a function that calls ipcRenderer.invoke to trigger the handler in your preload script.

To illustrate, we will add a global function to the renderer called ping() that will return a string from the main process.

First, set up the invoke call in your preload script:

preload.js

  1. const { contextBridge, ipcRenderer } = require('electron')
  2. contextBridge.exposeInMainWorld('versions', {
  3. node: () => process.versions.node,
  4. chrome: () => process.versions.chrome,
  5. electron: () => process.versions.electron,
  6. ping: () => ipcRenderer.invoke('ping')
  7. // we can also expose variables, not just functions
  8. })

Using Preload Scripts - 图5IPC security

Notice how we wrap the ipcRenderer.invoke('ping') call in a helper function rather than expose the ipcRenderer module directly via context bridge. You never want to directly expose the entire ipcRenderer module via preload. This would give your renderer the ability to send arbitrary IPC messages to the main process, which becomes a powerful attack vector for malicious code.

Then, set up your handle listener in the main process. We do this before loading the HTML file so that the handler is guaranteed to be ready before you send out the invoke call from the renderer.

main.js

  1. const { app, BrowserWindow, ipcMain } = require('electron')
  2. const path = require('node:path')
  3. const createWindow = () => {
  4. const win = new BrowserWindow({
  5. width: 800,
  6. height: 600,
  7. webPreferences: {
  8. preload: path.join(__dirname, 'preload.js')
  9. }
  10. })
  11. win.loadFile('index.html')
  12. }
  13. app.whenReady().then(() => {
  14. ipcMain.handle('ping', () => 'pong')
  15. createWindow()
  16. })

Once you have the sender and receiver set up, you can now send messages from the renderer to the main process through the 'ping' channel you just defined.

renderer.js

  1. const func = async () => {
  2. const response = await window.versions.ping()
  3. console.log(response) // prints out 'pong'
  4. }
  5. func()

Using Preload Scripts - 图6info

For more in-depth explanations on using the ipcRenderer and ipcMain modules, check out the full Inter-Process Communication guide.

Summary

A preload script contains code that runs before your web page is loaded into the browser window. It has access to both DOM APIs and Node.js environment, and is often used to expose privileged APIs to the renderer via the contextBridge API.

Because the main and renderer processes have very different responsibilities, Electron apps often use the preload script to set up inter-process communication (IPC) interfaces to pass arbitrary messages between the two kinds of processes.

In the next part of the tutorial, we will be showing you resources on adding more functionality to your app, then teaching you distributing your app to users.