Skip to main content

使用预加载脚本

学习目标

¥Learning goals

在本教程的这一部分中,你将了解什么是预加载脚本以及如何使用预加载脚本将特权 API 安全地公开到渲染器进程中。你还将学习如何使用 Electron 的进程间通信 (IPC) 模块在主进程和渲染进程之间进行通信。

¥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 的主进程是一个具有完全操作系统访问权限的 Node.js 环境。除了 Electron 模块 之外,你还可以访问 Node.js 内置组件 以及通过 npm 安装的任何软件包。另一方面,出于安全原因,渲染器进程默认运行网页并且不运行 Node.js。

¥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.

为了将 Electron 的不同进程类型桥接在一起,我们需要使用一个称为预加载的特殊脚本。

¥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

BrowserWindow 的预加载脚本在可以访问 HTML DOM 以及 Node.js 和 Electron API 的有限子集的上下文中运行。

¥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.

预加载脚本沙箱

从 Electron 20 开始,预加载脚本默认被沙箱化,并且不再能够访问完整的 Node.js 环境。实际上,这意味着你拥有一个 polyfilled require 函数,它只能访问一组有限的 API。

¥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.

可用的 API细节
Electron 模块渲染器进程模块
Node.js 模块eventstimersurl
Polyfill 全局变量BufferprocessclearImmediatesetImmediate

有关更多信息,请查看 进程沙箱 指南。

¥For more information, check out the Process Sandboxing guide.

预加载脚本在网页加载到渲染器之前注入,类似于 Chrome 扩展的 内容脚本。要向渲染器添加需要特权访问的功能,你可以通过 contextBridge API 定义 global 对象。

¥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.

为了演示这个概念,你将创建一个预加载脚本,将应用的 Chrome、Node 和 Electron 版本公开到渲染器中。

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

添加一个新的 preload.js 脚本,该脚本将 Electron 的 process.versions 对象的选定属性公开给 versions 全局变量中的渲染器进程。

¥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
const { contextBridge } = require('electron')

contextBridge.exposeInMainWorld('versions', {
node: () => process.versions.node,
chrome: () => process.versions.chrome,
electron: () => process.versions.electron
// we can also expose variables, not just functions
})

要将此脚本附加到渲染器进程,请将其路径传递给 BrowserWindow 构造函数中的 webPreferences.preload 选项:

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

main.js
const { app, BrowserWindow } = require('electron')
const path = require('node:path')

const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})

win.loadFile('index.html')
}

app.whenReady().then(() => {
createWindow()
})
信息

这里使用了两个 Node.js 概念:

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

  • __dirname 字符串指向当前正在执行的脚本的路径(在本例中为项目的根文件夹)。

    ¥The __dirname string points to the path of the currently executing script (in this case, your project's root folder).

  • path.join API 将多个路径段连接在一起,创建一个适用于所有平台的组合路径字符串。

    ¥The path.join API joins multiple path segments together, creating a combined path string that works across all platforms.

此时,渲染器可以访问 versions 全局变量,因此让我们在窗口中显示该信息。该变量可以通过 window.versions 或简单地 versions 访问。创建一个 renderer.js 脚本,该脚本使用 document.getElementById DOM API 将 HTML 元素的显示文本替换为 info 作为其 id 属性。

¥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
const information = document.getElementById('info')
information.innerText = `This app is using Chrome (v${versions.chrome()}), Node.js (v${versions.node()}), and Electron (v${versions.electron()})`

然后,通过添加一个以 info 作为其 id 属性的新元素来修改 index.html,并附加 renderer.js 脚本:

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

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'"
/>
<meta
http-equiv="X-Content-Security-Policy"
content="default-src 'self'; script-src 'self'"
/>
<title>Hello from Electron renderer!</title>
</head>
<body>
<h1>Hello from Electron renderer!</h1>
<p>👋</p>
<p id="info"></p>
</body>
<script src="./renderer.js"></script>
</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:

const { app, BrowserWindow } = require('electron/main')
const path = require('node:path')

const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})

win.loadFile('index.html')
}

app.whenReady().then(() => {
createWindow()

app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})

app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})

进程间通信

¥Communicating between processes

正如我们上面提到的,Electron 的主进程和渲染进程具有不同的职责,并且不可互换。这意味着无法直接从渲染器进程访问 Node.js API,也无法从主进程访问 HTML 文档对象模型 (DOM)。

¥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.

这个问题的解决方案是使用 Electron 的 ipcMainipcRenderer 模块进行进程间通信(IPC)。要将消息从网页发送到主进程,你可以使用 ipcMain.handle 设置主进程处理程序,然后公开一个调用 ipcRenderer.invoke 的函数以在预加载脚本中触发处理程序。

¥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.

为了说明这一点,我们将向渲染器添加一个名为 ping() 的全局函数,该函数将从主进程返回一个字符串。

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

首先,在预加载脚本中设置 invoke 调用:

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

preload.js
const { contextBridge, ipcRenderer } = require('electron')

contextBridge.exposeInMainWorld('versions', {
node: () => process.versions.node,
chrome: () => process.versions.chrome,
electron: () => process.versions.electron,
ping: () => ipcRenderer.invoke('ping')
// we can also expose variables, not just functions
})
工控机安全

请注意我们如何将 ipcRenderer.invoke('ping') 调用封装在辅助函数中,而不是通过上下文桥直接公开 ipcRenderer 模块。你永远不想通过预加载直接公开整个 ipcRenderer 模块。这将使你的渲染器能够向主进程发送任意 IPC 消息,这将成为恶意代码的强大攻击媒介。

¥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.

然后,在主进程中设置 handle 监听器。我们在加载 HTML 文件之前执行此操作,以便保证处理程序在从渲染器发出 invoke 调用之前准备就绪。

¥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
const { app, BrowserWindow, ipcMain } = require('electron/main')
const path = require('node:path')

const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
win.loadFile('index.html')
}
app.whenReady().then(() => {
ipcMain.handle('ping', () => 'pong')
createWindow()
})

设置好发送方和接收方后,你现在可以通过刚刚定义的 'ping' 通道将消息从渲染器发送到主进程。

¥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
const func = async () => {
const response = await window.versions.ping()
console.log(response) // prints out 'pong'
}

func()
信息

有关使用 ipcRendereripcMain 模块的更深入说明,请查看完整的 进程间通信 指南。

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

概括

¥Summary

预加载脚本包含在网页加载到浏览器窗口之前运行的代码。它可以访问 DOM API 和 Node.js 环境,并且通常用于通过 contextBridge API 向渲染器公开特权 API。

¥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.

由于主进程和渲染进程具有截然不同的职责,Electron 应用通常使用预加载脚本来设置进程间通信(IPC)接口,以在两种进程之间传递任意消息。

¥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.