跳到主要內容

進度條

總覽

進度條讓視窗能夠向使用者提供進度資訊,而無需切換到視窗本身。

在 Windows 上,您可以使用工作列按鈕來顯示進度條。

Windows Progress Bar

在 macOS 上,進度條將會顯示為 Dock 圖示的一部分。

macOS Progress Bar

在 Linux 上,Unity 圖形介面也有類似的功能,可讓您在啟動器中指定進度條。

Linux Progress Bar

注意:在 Windows 上,每個視窗都可以有自己的進度條,而在 macOS 和 Linux (Unity) 上,每個應用程式只能有一個進度條。


這三種情況都由同一個 API 涵蓋 - BrowserWindow 實例上的 setProgressBar() 方法。若要指示您的進度,請使用介於 01 之間的數字呼叫此方法。例如,如果您有一個長時間執行的任務目前已完成 63%,您可以呼叫它為 setProgressBar(0.63)

將參數設定為負值 (例如 -1) 將會移除進度條。將其設定為大於 1 的值將會在 Windows 中指示不確定的進度條,或在其他作業系統中箝制為 100%。不確定的進度條會保持活動狀態,但不顯示實際百分比,並且用於您不知道操作需要多長時間才能完成的情況。

請參閱 API 文件 以取得更多選項和模式。

範例

在此範例中,我們將進度條新增至主視窗,該進度條會使用 Node.js 計時器隨時間遞增。

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()
}
})

啟動 Electron 應用程式後,Dock (macOS) 或工作列 (Windows, Unity) 應顯示一個從零開始並進展到 100% 完成的進度條。然後它應該短暫顯示不確定 (Windows) 或固定在 100% (其他作業系統),然後循環。

macOS dock progress bar

對於 macOS,當使用 Mission Control 時,也會為您的應用程式指示進度條。

Mission Control Progress Bar