跳转到主要内容

使用预加载脚本

学习目标

在本教程中,你将学习什么是预加载脚本,以及如何使用它来安全地将特权 API 暴露给渲染进程。你还将学习如何使用 Electron 的进程间通信 (IPC) 模块在主进程和渲染进程之间进行通信。

什么是预加载脚本?

Electron 的主进程是一个 Node.js 环境,具有完全的操作系统访问权限。除了 Electron 模块 之外,你还可以访问 Node.js 内置模块,以及通过 npm 安装的任何包。另一方面,渲染进程运行网页,出于安全原因,默认情况下不运行 Node.js。

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

使用预加载脚本增强渲染器

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

预加载脚本沙箱化

从 Electron 20 开始,预加载脚本默认情况下被 沙箱化,不再具有访问完整 Node.js 环境的权限。实际上,这意味着你有一个具有 polyfilled require 函数的环境,该函数只能访问有限的 API 集。

可用 API详细信息
Electron 模块渲染进程模块
Node.js 模块events, timers, url
Polyfilled 全局对象Buffer, process, clearImmediate, setImmediate

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

预加载脚本在将网页加载到浏览器窗口之前运行,类似于 Chrome 扩展程序的 内容脚本。要向你的渲染器添加需要特权访问的功能,你可以通过 contextBridge API 定义 全局 对象。

为了演示这个概念,你将创建一个预加载脚本,将你的应用程序的 Chrome、Node 和 Electron 版本暴露给渲染器。

添加一个新的 preload.js 脚本,将 Electron 的 process.versions 对象的选定属性暴露给渲染进程,作为 versions 全局变量。

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 选项

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 概念

  • __dirname 字符串指向当前执行脚本的路径(在本例中,是你的项目根文件夹)。
  • path.join API 将多个路径段连接在一起,创建一个跨所有平台的组合路径字符串。

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

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()})`

然后,修改你的 index.html 文件,添加一个新的元素,其 id 属性为 info,并附加你的 renderer.js 脚本

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>

完成上述步骤后,你的应用程序应该如下所示

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

代码应该如下所示

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()
}
})

进程间通信

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

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

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

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

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
})
IPC 安全性

请注意,我们将在辅助函数中包装 ipcRenderer.invoke('ping') 调用,而不是通过 context bridge 直接暴露整个 ipcRenderer 模块。你 绝不 应该通过预加载直接暴露整个 ipcRenderer 模块。这将使你的渲染器能够向主进程发送任意 IPC 消息,这会成为恶意代码的强大攻击向量。

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

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' 通道从渲染器向主进程发送消息。

renderer.js
const func = async () => {
const response = await window.versions.ping()
console.log(response) // prints out 'pong'
}

func()
信息

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

总结

预加载脚本包含在网页加载到浏览器窗口之前运行的代码。它具有访问 DOM API 和 Node.js 环境的权限,通常用于通过 contextBridge API 将特权 API 暴露给渲染器。

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

在教程的下一部分中,我们将向你展示添加更多功能的资源,然后教你如何将你的应用程序分发给用户。