这一讲会重点介绍如何集成 Node.js、使用 preload 脚本、进程间双向通信、上下文隔离等,为大家揭开 Electron 更强大的能力。
集成 Node.js
企业级桌面应用的资源都是本地化的,离线也能使用,所以需要把 html、js、css 这些资源都打包进去,接下来我们就在 src/renderer 目录下创建 index.html 和 index.js 两个文件:
<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>Electron Desktop</title></head><body><p id="platform">操作系统:</p><p id="release">版本号:</p><script src="./index.js"></script></body>
</html>
然后在创建窗口函数里面把用 loadURL 加载网页的代码换成 loadFile 加载本地文件:
function createWindow() {mainWindow = new BrowserWindow({ width: 800, height: 600 })mainWindow.loadFile(path.join(__dirname, '../renderer/index.html'))
}
这样就可以加载本地 HTML 文件了,接下来要实现本节第一个需求:
- 获取用户当前操作系统及其版本号并展示在页面上
传统的 Web 网页运行在浏览器沙箱环境里面,没有能力调用操作系统 API,但是 Electron 就不一样了,它支持在 Web 中执行 Node.js 代码。不过这个能力默认是不开启的,要想使用这个能力,必须在创建窗口的时候指定两个参数:
nodeIntegration: true
:开启 node.js 环境集成contextIsolation: false
:关闭上下文隔离
function createWindow() {mainWindow = new BrowserWindow({width: 800,height: 600,webPreferences: {nodeIntegration: true,contextIsolation: false,},})mainWindow.loadFile(path.join(__dirname, '../renderer/index.html'))
}
然后就可以在 src/renderer/index.js 中调用 node.js 的方法:
const os = require('os')
const platform = os.platform()
const release = os.release()
document.getElementById('platform').append(platform)
document.getElementById('release').append(release)
运行程序会发现操作系统和版本号已经显示出来了:
使用 preload 脚本
直接在网页上调用 node.js 的 API 虽然很爽,但是风险极大,尤其是加载一个第三方的 Web 页面的时候,可能会被植入恶意脚本(例如调用 fs 模块删除文件等)。因此,Electron 官方不推荐开启 nodeIntegration,而是建议大家使用加载 preload 脚本的方式:
function createWindow() {mainWindow = new BrowserWindow({width: 800,height: 600,webPreferences: {nodeIntegration: false, // 不开启 node 集成preload: path.join(__dirname, '../preload/index.js'), // 在 preload 脚本中访问 node 的 API},})mainWindow.loadFile(path.join(__dirname, '../renderer/index.html'))
}
preload 脚本是特殊的 JS 脚本,由 Electron 注入到 index.html 当中,会早于 index.html 文件中引入的其他脚本,而且它有权限访问 node.js 的 API,无论用户是否开启了 nodeIntegration。我们把 src/renderer/index.js 的内容删除,改成仅打印一行文字:
console.log('renderer index.js')
然后在 src 目录下新增 prel