进度条
概述
进度条允许窗口在无需切换到窗口本身的情况下向用户提供进度信息。
在 Windows 上,您可以使用任务栏按钮显示进度条。

在 macOS 上,进度条将显示为 Dock 图标的一部分。

在 Linux 上,Unity 图形界面也有类似的功能,允许您在启动器中指定进度条。

注意:在 Windows 上,每个窗口都可以有自己的进度条,而在 macOS 和 Linux (Unity) 上,应用程序只能有一个进度条。
所有这三种情况都由同一个 API 覆盖 - `BrowserWindow` 实例上提供的 setProgressBar() 方法。要指示您的进度,请使用介于 0 和 1 之间的数字调用此方法。例如,如果有一个耗时任务当前已完成 63%,您将调用 setProgressBar(0.63)。
将参数设置为负值(例如 -1)将删除进度条。将其设置为大于 1 的值将在 Windows 上显示不确定进度条,或者在其他操作系统上将其限制为 100%。不确定进度条保持活动状态,但不显示实际百分比,用于您不知道操作需要多长时间才能完成的情况。
有关更多选项和模式,请参阅 API 文档。
示例
在此示例中,我们为主窗口添加一个进度条,该进度条使用 Node.js 定时器随时间递增。
- main.js
- index.html
const { app, BrowserWindow } = require('electron/main')
let progressInterval
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.loadFile('index.html')
const INCREMENT = 0.03
const INTERVAL_DELAY = 100 // ms
let c = 0
progressInterval = setInterval(() => {
// update progress bar to next value
// values between 0 and 1 will show progress, >1 will show indeterminate or stick at 100%
win.setProgressBar(c)
// increment or reset progress bar
if (c < 2) {
c += INCREMENT
} else {
c = (-INCREMENT * 5) // reset to a bit less than 0 to show reset state
}
}, INTERVAL_DELAY)
}
app.whenReady().then(createWindow)
// before the app is terminated, clear both timers
app.on('before-quit', () => {
clearInterval(progressInterval)
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<h1>Hello World!</h1>
<p>Keep an eye on the dock (Mac) or taskbar (Windows, Unity) for this application!</p>
<p>It should indicate a progress that advances from 0 to 100%.</p>
<p>It should then show indeterminate (Windows) or pin at 100% (other operating systems)
briefly and then loop.</p>
</body>
</html>
启动 Electron 应用程序后,Dock (macOS) 或任务栏 (Windows, Unity) 应显示一个进度条,该进度条从零开始,逐渐完成到 100%。然后,它将在短暂显示不确定 (Windows) 或固定到 100% (其他操作系统) 后循环。

对于 macOS,在使用 Mission Control 时,您的应用程序也会显示进度条。
