進度條
概述
進度條可讓視窗向使用者提供進度資訊,而無需切換到視窗本身。
在 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 時,也會顯示您的應用程式的進度條