进度条
概述
进度条允许窗口向用户提供进度信息,而无需切换到窗口本身。
在 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 时,也会为您的应用程序指示进度条。