Electron原来叫Atom Shell ,可以用Web技术搭建桌面端程序,以Electron为基础,可以用HTML,CSS和javascriptpt实现程序逻辑和用户桌面,Electron程序一般有主进程和渲染进程,主进程是启动程序的Node脚本,提供对原生的node模块访问。渲染进程是由chromium管理的Web界面。以下的内容介绍从零开始搭建一个读取本地文件的Electron项目。
一 运行简单项目
1.获取electron-quick-start基础项目
electron-quick-start项目是gitHub上提供的简单electron项目模板,包含运行基本Electron程序所必需的依赖项,获取这个项目,安装依赖项命令如下:
git clone https://github.com/atom/electron-quick-start
cd electron-quick-start
npm install
2. 运行与调试
运行命令代码如下:
npm run start
在win10上运行electron-quick-start项目效果如下所示:
注意:调试命令如下 ctrl+shift+i
在此项目中,主进程是main.js,渲染进程是index.html,preload.js是主进程中的预装载代码,renderer.js是渲染进程中渲染代码。
二 读取本地文件
1.渲染进程index.html代码
首行在渲染进程index.html中增加一个<pre>标签用于展示读取的本地文件内容,代码如下所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'">
<link href="./styles.css" rel="stylesheet">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
We are using Node.js <span id="node-version"></span>,
Chromium <span id="chrome-version"></span>,
and Electron <span id="electron-version"></span>.
<pre id="source"></pre>
<!-- You can also require other files to run in this process -->
<script src="./renderer.js"></script>
</body>
</html>
2. 主进程main.js
在主进程的BrowserWindow中,我们传递一个配置参数webPreferences,它的可配置项:
nodeIntegration: 是否集成node.js默认为false
contextIsoIation: 上下文隔离,默认为true
preload : 指定预加载的js文件绝对路径
只要把noteIntegration和contextIsolation配置为true和false即可,但这是一种不安全的行为,在Electron中,它推荐在preload中操作node, 主进程main.js代码如下
// Modules to control application life and create native browser window
const { app, BrowserWindow } = require('electron')
const path = require('node:path')
function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
preload: path.join(__dirname, 'preload.js')
}
})
// and load the index.html of the app.
mainWindow.loadFile('index.html')
// Open the DevTools.
// mainWindow.webContents.openDevTools()
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
此时我们就可以在preload.js操作node.js ,代码如下:
//preload.js
console.log(process.platform)
此时运行,使用调试模式可以查看自己电脑操作系统,此时仅能在preload中操作node.js。
3.主进程子代码preload.js
Electron提供一个api为contextBridge,contextBridge在Electron中用于在主进程和渲染进程之间建立安全的通信通道,它提供的主要API有:
exposeInMainWorld(apiKey,api):
apiKey: string 将API挂载到window的键。 API可通过windows[apikey]访问。
api: any 需要映射的node.js模块。
exposeInIsolatedWorld(worldId, apiKey, api):
worldId Integer 要注入的API的ID,0是默认使用ID,999是Electron中的contextIsolation使用的ID,使用999将在preload上下文暴露对象,建议使用1000+创建隔离的world。
apiKey: string 将API挂载到window的键。 API可通过windows[apikey]访问。
api: any 需要映射的node.js模块
在此项目中,使用exposeInMainWorld在主进程与渲染进程之间,建立安全通道,代码如下:
/**
* The preload script runs before `index.html` is loaded
* in the renderer. It has access to web APIs as well as
* Electron's renderer process modules and some polyfilled
* Node.js functions.
*
* https://www.electronjs.org/docs/latest/tutorial/sandbox
*/
const { contextBridge }=require("electron")
const fs=require('fs')
contextBridge.exposeInMainWorld('electronfs',fs)
window.addEventListener('DOMContentLoaded', () => {
const replaceText = (selector, text) => {
const element = document.getElementById(selector)
if (element) element.innerText = text
}
for (const type of ['chrome', 'node', 'electron']) {
replaceText(`${type}-version`, process.versions[type])
}
})
4.渲染进程子代码renderer.js
renderer.js是渲染进程的子代码,通过<script src='./renderer.js'></script>引入到渲染进程, 代码如下:
/**
* This file is loaded via the <script> tag in the index.html file and will
* be executed in the renderer process for that window. No Node.js APIs are
* available in this process because `nodeIntegration` is turned off and
* `contextIsolation` is turned on. Use the contextBridge API in `preload.js`
* to expose Node.js functionality from the main process.
*/
electronfs.readFile('./main.js','utf8',(err,data)=>{
if(err) {
console.err('读取文件失败',err)
} else {
document.getElementById("source").innerHTML=data
}
})
使用npm run start 运行后,效果如下:
此文主要介绍如何使用Electron操作fs模块,读取本地文件main.js内容,并在浏览窗口中显示 。主要有获取electron-quick-start项目并运行,建立主进程和渲染进程之间安全通道,在渲染进程中使用node.js 的fs模块读取本地文件main.js并在浏览窗口中显示。