跳到主要內容

重大變更

重大變更將在此記錄,並且在 JS 程式碼中,盡可能地加入棄用警告,至少在變更發生前一個主要版本

重大變更的類型

此文件使用以下慣例來分類重大變更

  • API 已變更: API 變更的方式,使得未更新的程式碼保證會拋出例外。
  • 行為已變更: Electron 的行為已變更,但並非一定會拋出例外。
  • 預設值已變更: 依賴舊預設值的程式碼可能會損壞,但不一定會拋出例外。可以明確指定值來還原舊的行為。
  • 已棄用: API 已標示為棄用。API 將繼續運作,但會發出棄用警告,並將在未來的版本中移除。
  • 已移除: API 或功能已移除,不再受 Electron 支援。

計劃中的重大 API 變更 (35.0)

已棄用:WebContentsconsole-message 事件中的 levelmessagelinesourceId 引數

WebContents 上的 console-message 事件已更新,以提供 Event 引數的詳細資訊。

// Deprecated
webContents.on('console-message', (event, level, message, line, sourceId) => {})

// Replace with:
webContents.on('console-message', ({ level, message, lineNumber, sourceId, frame }) => {})

此外,level 現在是一個字串,可能的值為 infowarningerrordebug

計劃中的重大 API 變更 (34.0)

行為已變更:在 Windows 上全螢幕時,功能表列將會隱藏

這使行為與 Linux 一致。先前的行為:在 Windows 上全螢幕時,功能表列仍然可見。新的行為:在 Windows 上全螢幕時,功能表列將會隱藏。

更正:先前將此列為 Electron 33 中的重大變更,但實際上是在 Electron 34 中首次發佈。

計劃中的重大 API 變更 (33.0)

行為已變更:frame 屬性可能會擷取已分離的 WebFrameMain 執行個體,或完全不擷取

提供存取 WebFrameMain 執行個體的 API,可能會傳回 frame.detached 設定為 true 的執行個體,或可能傳回 null

當框架執行跨來源導覽時,它會進入分離狀態,其中它不再附加到頁面。在此狀態下,它可能會在被刪除之前執行 卸載處理常式。在此狀態期間傳送 IPC 的情況下,frame.detached 將設定為 true,並且該框架會在不久之後銷毀。

當接收事件時,務必在收到後立即存取 WebFrameMain 屬性。否則,無法保證它指向與接收時相同的網頁。為了避免錯位的期望,如果網頁已變更,Electron 將在延遲存取的情況下傳回 null

ipcMain.on('unload-event', (event) => {
event.senderFrame; // ✅ accessed immediately
});

ipcMain.on('unload-event', async (event) => {
await crossOriginNavigationPromise;
event.senderFrame; // ❌ returns `null` due to late access
});

行為已變更:Windows 上的自訂通訊協定 URL 處理

由於 Chromium 為了支援 非特殊配置 URL 而進行的變更,使用 Windows 檔案路徑的自訂通訊協定 URL 將無法與已棄用的 protocol.registerFileProtocol 以及 BrowserWindow.loadURLWebContents.loadURL<webview>.loadURL 上的 baseURLForDataURL 屬性正確運作。protocol.handle 也無法與這些類型的 URL 運作,但這不是變更,因為它一直都是這樣運作。

// No longer works
protocol.registerFileProtocol('other', () => {
callback({ filePath: '/path/to/my/file' })
})

const mainWindow = new BrowserWindow()
mainWindow.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: 'other://C:\\myapp' })
mainWindow.loadURL('other://C:\\myapp\\index.html')

// Replace with
const path = require('node:path')
const nodeUrl = require('node:url')
protocol.handle(other, (req) => {
const srcPath = 'C:\\myapp\\'
const reqURL = new URL(req.url)
return net.fetch(nodeUrl.pathToFileURL(path.join(srcPath, reqURL.pathname)).toString())
})

mainWindow.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: 'other://' })
mainWindow.loadURL('other://index.html')

行為已變更:apploginwebContents 屬性

當從使用 respondToAuthRequestsFromMainProcess 選項建立的公用程式程序發出請求時,applogin 事件的 webContents 屬性將為 null

已棄用:BrowserWindowConstructorOption.type 中的 textured 選項

BrowserWindowConstructorOptionstypetextured 選項已棄用,沒有替代選項。此選項依賴 macOS 上的 NSWindowStyleMaskTexturedBackground 樣式遮罩,該遮罩已棄用且沒有替代方案。

已移除:macOS 10.15 支援

Chromium 不再支援 macOS 10.15 (Catalina)。

舊版的 Electron 將繼續在 Catalina 上執行,但需要 macOS 11 (Big Sur) 或更新版本才能執行 Electron v33.0.0 及更高版本。

已棄用:systemPreferences.accessibilityDisplayShouldReduceTransparency

現在已棄用 systemPreferences.accessibilityDisplayShouldReduceTransparency 屬性,而改用新的 nativeTheme.prefersReducedTransparency,它提供相同的資訊並可跨平台運作。

// Deprecated
const shouldReduceTransparency = systemPreferences.accessibilityDisplayShouldReduceTransparency

// Replace with:
const prefersReducedTransparency = nativeTheme.prefersReducedTransparency

計劃中的重大 API 變更 (32.0)

已移除:File.path

在早期版本的 Electron 中,為了方便在轉譯器中更常見地處理原生檔案,新增了 Web File 物件的非標準 path 屬性。然而,它代表與標準的偏差,並且也存在輕微的安全風險,因此從 Electron 32.0 開始,它已被移除,並改用 webUtils.getPathForFile 方法。

// Before (renderer)

const file = document.querySelector('input[type=file]').files[0]
alert(`Uploaded file path was: ${file.path}`)
// After (renderer)

const file = document.querySelector('input[type=file]').files[0]
electron.showFilePath(file)

// (preload)
const { contextBridge, webUtils } = require('electron')

contextBridge.exposeInMainWorld('electron', {
showFilePath (file) {
// It's best not to expose the full file path to the web content if
// possible.
const path = webUtils.getPathForFile(file)
alert(`Uploaded file path was: ${path}`)
}
})

已棄用:WebContents 上的 clearHistorycanGoBackgoBackcanGoForwardgoForwardgoToIndexcanGoToOffsetgoToOffset

現在已棄用與導覽相關的 API。

這些 API 已移至 WebContentsnavigationHistory 屬性,以提供更結構化和直觀的介面來管理導覽歷史記錄。

// Deprecated
win.webContents.clearHistory()
win.webContents.canGoBack()
win.webContents.goBack()
win.webContents.canGoForward()
win.webContents.goForward()
win.webContents.goToIndex(index)
win.webContents.canGoToOffset()
win.webContents.goToOffset(index)

// Replace with
win.webContents.navigationHistory.clear()
win.webContents.navigationHistory.canGoBack()
win.webContents.navigationHistory.goBack()
win.webContents.navigationHistory.canGoForward()
win.webContents.navigationHistory.goForward()
win.webContents.navigationHistory.canGoToOffset()
win.webContents.navigationHistory.goToOffset(index)

計劃中的重大 API 變更 (31.0)

已移除:WebSQL 支援

Chromium 已移除對上游 WebSQL 的支援,將其轉移至僅限 Android。請參閱Chromium 的移除意圖討論以取得更多資訊。

行為變更:nativeImage.toDataURL 將保留 PNG 色彩空間

PNG 解碼器實作已變更為保留色彩空間資料,此函式傳回的編碼資料現在與其相符。

請參閱crbug.com/332584706以取得更多資訊。

行為變更:window.flashFrame(bool) 將在 macOS 上持續閃爍 Dock 圖示

這使行為與 Windows 和 Linux 一致。先前的行為:第一個 flashFrame(true) 只會彈跳一次 Dock 圖示(使用 NSInformationalRequest 層級),而 flashFrame(false) 不會執行任何操作。新的行為:持續閃爍直到呼叫 flashFrame(false)。這會改用 NSCriticalRequest 層級。若要明確使用 NSInformationalRequest 導致 Dock 圖示彈跳一次,仍然可以使用 dock.bounce('informational')

計畫中的重大 API 變更 (30.0)

行為變更:跨來源 iframe 現在使用權限政策來存取功能

跨來源 iframe 現在必須透過 allow 屬性指定給定 iframe 可用的功能,才能存取它們。

請參閱文件以取得更多資訊。

已移除:--disable-color-correct-rendering 開關

此開關從未正式記錄,但此處仍註明其移除。Chromium 本身現在對色彩空間有更好的支援,因此不應需要此旗標。

行為變更:macOS 上的 BrowserView.setAutoResize 行為

在 Electron 30 中,BrowserView 現在是新 WebContentsView API 的包裝器。

先前,BrowserView API 的 setAutoResize 函式由 macOS 上的 自動調整大小以及 Windows 和 Linux 上的自訂演算法所支援。對於簡單的使用案例,例如讓 BrowserView 填滿整個視窗,這兩種方法的行為相同。然而,在更進階的案例中,macOS 上的 BrowserView 的自動調整大小方式會與其他平台不同,因為 Windows 和 Linux 的自訂調整大小演算法與 macOS 的自動調整大小 API 的行為不完全相符。現在,自動調整大小的行為在所有平台上都已標準化。

如果您的應用程式使用 BrowserView.setAutoResize 來執行比讓 BrowserView 填滿整個視窗更複雜的操作,您很可能已設定自訂邏輯來處理 macOS 上行為的此差異。如果是這樣,由於自動調整大小的行為一致,因此在 Electron 30 中不再需要該邏輯。

已棄用:BrowserView

BrowserView 類別已棄用,並由新的 WebContentsView 類別取代。

BrowserWindow 中的 BrowserView 相關方法也已棄用

BrowserWindow.fromBrowserView(browserView)
win.setBrowserView(browserView)
win.getBrowserView()
win.addBrowserView(browserView)
win.removeBrowserView(browserView)
win.setTopBrowserView(browserView)
win.getBrowserViews()

已移除:WebContentscontext-menuparams.inputFormType 屬性

已移除來自 WebContentscontext-menu 事件中 params 物件的 inputFormType 屬性。請改用新的 formControlType 屬性。

已移除:process.getIOCounters()

Chromium 已移除對此資訊的存取權。

計畫中的重大 API 變更 (29.0)

行為變更:ipcRenderer 無法再透過 contextBridge 傳送

嘗試透過 contextBridge 將整個 ipcRenderer 模組以物件形式傳送,現在會在橋接的接收端產生一個空物件。此變更是為了移除/減輕安全性漏洞。您不應透過橋接直接公開 ipcRenderer 或其方法。相反地,請提供如下的安全包裝函式

contextBridge.exposeInMainWorld('app', {
onEvent: (cb) => ipcRenderer.on('foo', (e, ...args) => cb(args))
})

已移除:app 上的 renderer-process-crashed 事件

已移除 app 上的 renderer-process-crashed 事件。請改用新的 render-process-gone 事件。

// Removed
app.on('renderer-process-crashed', (event, webContents, killed) => { /* ... */ })

// Replace with
app.on('render-process-gone', (event, webContents, details) => { /* ... */ })

已移除:WebContents<webview> 上的 crashed 事件

已移除 WebContents<webview> 上的 crashed 事件。請改用新的 render-process-gone 事件。

// Removed
win.webContents.on('crashed', (event, killed) => { /* ... */ })
webview.addEventListener('crashed', (event) => { /* ... */ })

// Replace with
win.webContents.on('render-process-gone', (event, details) => { /* ... */ })
webview.addEventListener('render-process-gone', (event) => { /* ... */ })

已移除:app 上的 gpu-process-crashed 事件

已移除 app 上的 gpu-process-crashed 事件。請改用新的 child-process-gone 事件。

// Removed
app.on('gpu-process-crashed', (event, killed) => { /* ... */ })

// Replace with
app.on('child-process-gone', (event, details) => { /* ... */ })

計畫中的重大 API 變更 (28.0)

行為變更:將 WebContents.backgroundThrottling 設定為 false 會影響主機 BrowserWindow 中的所有 WebContents

WebContents.backgroundThrottling 設定為 false 將會針對其顯示的所有 WebContentsBrowserWindow 中停用影格節流。

已移除:BrowserWindow.setTrafficLightPosition(position)

已移除 BrowserWindow.setTrafficLightPosition(position),應改用 BrowserWindow.setWindowButtonPosition(position) API,它接受 null 而非 { x: 0, y: 0 } 以將位置重設為系統預設值。

// Removed in Electron 28
win.setTrafficLightPosition({ x: 10, y: 10 })
win.setTrafficLightPosition({ x: 0, y: 0 })

// Replace with
win.setWindowButtonPosition({ x: 10, y: 10 })
win.setWindowButtonPosition(null)

已移除:BrowserWindow.getTrafficLightPosition()

已移除 BrowserWindow.getTrafficLightPosition(),應改用 BrowserWindow.getWindowButtonPosition() API,當沒有自訂位置時,它會傳回 null 而非 { x: 0, y: 0 }

// Removed in Electron 28
const pos = win.getTrafficLightPosition()
if (pos.x === 0 && pos.y === 0) {
// No custom position.
}

// Replace with
const ret = win.getWindowButtonPosition()
if (ret === null) {
// No custom position.
}

已移除:ipcRenderer.sendTo()

已移除 ipcRenderer.sendTo() API。應改為在轉譯器之間設定 MessageChannel

也已移除 IpcRendererEventsenderIdsenderIsMainFrame 屬性。

已移除:app.runningUnderRosettaTranslation

已移除 app.runningUnderRosettaTranslation 屬性。請改用 app.runningUnderARM64Translation

// Removed
console.log(app.runningUnderRosettaTranslation)
// Replace with
console.log(app.runningUnderARM64Translation)

已棄用:app 上的 renderer-process-crashed 事件

app 上的 renderer-process-crashed 事件已棄用。請改用新的 render-process-gone 事件。

// Deprecated
app.on('renderer-process-crashed', (event, webContents, killed) => { /* ... */ })

// Replace with
app.on('render-process-gone', (event, webContents, details) => { /* ... */ })

已棄用:WebContentscontext-menuparams.inputFormType 屬性

已棄用來自 WebContentscontext-menu 事件中 params 物件的 inputFormType 屬性。請改用新的 formControlType 屬性。

已棄用:WebContents<webview> 上的 crashed 事件

WebContents<webview> 上的 crashed 事件已被棄用。請改用新的 render-process-gone 事件。

// Deprecated
win.webContents.on('crashed', (event, killed) => { /* ... */ })
webview.addEventListener('crashed', (event) => { /* ... */ })

// Replace with
win.webContents.on('render-process-gone', (event, details) => { /* ... */ })
webview.addEventListener('render-process-gone', (event) => { /* ... */ })

已棄用:app 上的 gpu-process-crashed 事件

app 上的 gpu-process-crashed 事件已被棄用。請改用新的 child-process-gone 事件。

// Deprecated
app.on('gpu-process-crashed', (event, killed) => { /* ... */ })

// Replace with
app.on('child-process-gone', (event, details) => { /* ... */ })

計畫中的重大 API 變更 (27.0)

已移除:macOS 10.13 / 10.14 支援

macOS 10.13 (High Sierra) 和 macOS 10.14 (Mojave) 已不再受 Chromium 支援。

舊版的 Electron 將繼續在這些作業系統上執行,但執行 Electron v27.0.0 及更高版本需要 macOS 10.15 (Catalina) 或更高版本。

已棄用:ipcRenderer.sendTo()

ipcRenderer.sendTo() API 已被棄用。應改為在渲染器之間設定 MessageChannel

IpcRendererEventsenderIdsenderIsMainFrame 屬性也已被棄用。

已移除:systemPreferences 中的顏色配置事件

已移除下列 systemPreferences 事件

  • inverted-color-scheme-changed
  • high-contrast-color-scheme-changed

請改用 nativeTheme 模組上的新 updated 事件。

// Removed
systemPreferences.on('inverted-color-scheme-changed', () => { /* ... */ })
systemPreferences.on('high-contrast-color-scheme-changed', () => { /* ... */ })

// Replace with
nativeTheme.on('updated', () => { /* ... */ })

已移除:macOS 上的一些 window.setVibrancy 選項

已移除下列 vibrancy 選項

  • 'light'
  • 'medium-light'
  • 'dark'
  • 'ultra-dark'
  • 'appearance-based'

這些選項先前已被棄用,並且已由 Apple 在 10.15 版本中移除。

已移除:webContents.getPrinters

webContents.getPrinters 方法已移除。請改用 webContents.getPrintersAsync

const w = new BrowserWindow({ show: false })

// Removed
console.log(w.webContents.getPrinters())
// Replace with
w.webContents.getPrintersAsync().then((printers) => {
console.log(printers)
})

已移除:systemPreferences.{get,set}AppLevelAppearancesystemPreferences.appLevelAppearance

已移除 systemPreferences.getAppLevelAppearancesystemPreferences.setAppLevelAppearance 方法,以及 systemPreferences.appLevelAppearance 屬性。請改用 nativeTheme 模組。

// Removed
systemPreferences.getAppLevelAppearance()
// Replace with
nativeTheme.shouldUseDarkColors

// Removed
systemPreferences.appLevelAppearance
// Replace with
nativeTheme.shouldUseDarkColors

// Removed
systemPreferences.setAppLevelAppearance('dark')
// Replace with
nativeTheme.themeSource = 'dark'

已移除:systemPreferences.getColoralternate-selected-control-text

已移除 systemPreferences.getColoralternate-selected-control-text 值。請改用 selected-content-background

// Removed
systemPreferences.getColor('alternate-selected-control-text')
// Replace with
systemPreferences.getColor('selected-content-background')

計畫中的重大 API 變更 (26.0)

已棄用:webContents.getPrinters

webContents.getPrinters 方法已棄用。請改用 webContents.getPrintersAsync

const w = new BrowserWindow({ show: false })

// Deprecated
console.log(w.webContents.getPrinters())
// Replace with
w.webContents.getPrintersAsync().then((printers) => {
console.log(printers)
})

已棄用:systemPreferences.{get,set}AppLevelAppearancesystemPreferences.appLevelAppearance

systemPreferences.getAppLevelAppearancesystemPreferences.setAppLevelAppearance 方法,以及 systemPreferences.appLevelAppearance 屬性已棄用。請改用 nativeTheme 模組。

// Deprecated
systemPreferences.getAppLevelAppearance()
// Replace with
nativeTheme.shouldUseDarkColors

// Deprecated
systemPreferences.appLevelAppearance
// Replace with
nativeTheme.shouldUseDarkColors

// Deprecated
systemPreferences.setAppLevelAppearance('dark')
// Replace with
nativeTheme.themeSource = 'dark'

已棄用:systemPreferences.getColoralternate-selected-control-text

systemPreferences.getColoralternate-selected-control-text 值已棄用。請改用 selected-content-background

// Deprecated
systemPreferences.getColor('alternate-selected-control-text')
// Replace with
systemPreferences.getColor('selected-content-background')

計畫中的重大 API 變更 (25.0)

已棄用:protocol.{un,}{register,intercept}{Buffer,String,Stream,File,Http}Protocolprotocol.isProtocol{Registered,Intercepted}

protocol.register*Protocolprotocol.intercept*Protocol 方法已由 protocol.handle 取代。

新方法可以註冊新的協定或攔截現有的協定,並且回應可以是任何類型。

// Deprecated in Electron 25
protocol.registerBufferProtocol('some-protocol', () => {
callback({ mimeType: 'text/html', data: Buffer.from('<h5>Response</h5>') })
})

// Replace with
protocol.handle('some-protocol', () => {
return new Response(
Buffer.from('<h5>Response</h5>'), // Could also be a string or ReadableStream.
{ headers: { 'content-type': 'text/html' } }
)
})
// Deprecated in Electron 25
protocol.registerHttpProtocol('some-protocol', () => {
callback({ url: 'https://electron.dev.org.tw' })
})

// Replace with
protocol.handle('some-protocol', () => {
return net.fetch('https://electron.dev.org.tw')
})
// Deprecated in Electron 25
protocol.registerFileProtocol('some-protocol', () => {
callback({ filePath: '/path/to/my/file' })
})

// Replace with
protocol.handle('some-protocol', () => {
return net.fetch('file:///path/to/my/file')
})

已棄用:BrowserWindow.setTrafficLightPosition(position)

BrowserWindow.setTrafficLightPosition(position) 已被棄用,應改用接受 null 而非 { x: 0, y: 0 }BrowserWindow.setWindowButtonPosition(position) API,以將位置重置為系統預設值。

// Deprecated in Electron 25
win.setTrafficLightPosition({ x: 10, y: 10 })
win.setTrafficLightPosition({ x: 0, y: 0 })

// Replace with
win.setWindowButtonPosition({ x: 10, y: 10 })
win.setWindowButtonPosition(null)

已棄用:BrowserWindow.getTrafficLightPosition()

BrowserWindow.getTrafficLightPosition() 已被棄用,應改用 BrowserWindow.getWindowButtonPosition() API,當沒有自訂位置時,該 API 會傳回 null 而非 { x: 0, y: 0 }

// Deprecated in Electron 25
const pos = win.getTrafficLightPosition()
if (pos.x === 0 && pos.y === 0) {
// No custom position.
}

// Replace with
const ret = win.getWindowButtonPosition()
if (ret === null) {
// No custom position.
}

計畫中的重大 API 變更 (24.0)

API 已變更:nativeImage.createThumbnailFromPath(path, size)

maxSize 參數已變更為 size,以反映傳入的大小將會是建立的縮圖大小。先前,如果影像小於 maxSize,Windows 不會放大影像,而 macOS 則總是將大小設定為 maxSize。現在,在各個平台上,行為都相同了。

已更新的行為

// a 128x128 image.
const imagePath = path.join('path', 'to', 'capybara.png')

// Scaling up a smaller image.
const upSize = { width: 256, height: 256 }
nativeImage.createThumbnailFromPath(imagePath, upSize).then(result => {
console.log(result.getSize()) // { width: 256, height: 256 }
})

// Scaling down a larger image.
const downSize = { width: 64, height: 64 }
nativeImage.createThumbnailFromPath(imagePath, downSize).then(result => {
console.log(result.getSize()) // { width: 64, height: 64 }
})

先前的行為 (在 Windows 上)

// a 128x128 image
const imagePath = path.join('path', 'to', 'capybara.png')
const size = { width: 256, height: 256 }
nativeImage.createThumbnailFromPath(imagePath, size).then(result => {
console.log(result.getSize()) // { width: 128, height: 128 }
})

計畫中的重大 API 變更 (23.0)

行為已變更:macOS 上的可拖曳區域

macOS 上可拖曳區域的實作 (使用 CSS 屬性 -webkit-app-region: drag) 已變更,使其與 Windows 和 Linux 一致。先前,當具有 -webkit-app-region: no-drag 的區域與具有 -webkit-app-region: drag 的區域重疊時,無論 CSS 圖層如何,no-drag 區域在 macOS 上總是優先。也就是說,如果 drag 區域在 no-drag 區域之上,它將會被忽略。從 Electron 23 開始,在 no-drag 區域之上的 drag 區域將會正確地使該區域可拖曳。

此外,customButtonsOnHover BrowserWindow 屬性先前建立了一個忽略 -webkit-app-region CSS 屬性的可拖曳區域。現在已修正此問題 (請參閱 #37210 了解討論)。

因此,如果您的應用程式在 macOS 上使用具有可拖曳區域的無邊框視窗,則您的應用程式中可拖曳的區域可能會在 Electron 23 中變更。

已移除:Windows 7 / 8 / 8.1 支援

不再支援 Windows 7、Windows 8 和 Windows 8.1。Electron 遵循計畫中的 Chromium 棄用原則,該原則將自 Chromium 109 開始棄用 Windows 7 支援

舊版的 Electron 將繼續在這些作業系統上執行,但執行 Electron v23.0.0 及更高版本需要 Windows 10 或更高版本。

已移除:BrowserWindow scroll-touch-* 事件

已移除 BrowserWindow 上已棄用的 scroll-touch-beginscroll-touch-endscroll-touch-edge 事件。請改為使用 WebContents 上新提供的 input-event 事件

// Removed in Electron 23.0
win.on('scroll-touch-begin', scrollTouchBegin)
win.on('scroll-touch-edge', scrollTouchEdge)
win.on('scroll-touch-end', scrollTouchEnd)

// Replace with
win.webContents.on('input-event', (_, event) => {
if (event.type === 'gestureScrollBegin') {
scrollTouchBegin()
} else if (event.type === 'gestureScrollUpdate') {
scrollTouchEdge()
} else if (event.type === 'gestureScrollEnd') {
scrollTouchEnd()
}
})

已移除:webContents.incrementCapturerCount(stayHidden, stayAwake)

webContents.incrementCapturerCount(stayHidden, stayAwake) 函式已被移除。現在當頁面擷取完成時,會由 webContents.capturePage 自動處理。

const w = new BrowserWindow({ show: false })

// Removed in Electron 23
w.webContents.incrementCapturerCount()
w.capturePage().then(image => {
console.log(image.toDataURL())
w.webContents.decrementCapturerCount()
})

// Replace with
w.capturePage().then(image => {
console.log(image.toDataURL())
})

已移除:webContents.decrementCapturerCount(stayHidden, stayAwake)

webContents.decrementCapturerCount(stayHidden, stayAwake) 函式已被移除。現在當頁面擷取完成時,會由 webContents.capturePage 自動處理。

const w = new BrowserWindow({ show: false })

// Removed in Electron 23
w.webContents.incrementCapturerCount()
w.capturePage().then(image => {
console.log(image.toDataURL())
w.webContents.decrementCapturerCount()
})

// Replace with
w.capturePage().then(image => {
console.log(image.toDataURL())
})

計畫性重大 API 變更 (22.0)

已棄用:webContents.incrementCapturerCount(stayHidden, stayAwake)

webContents.incrementCapturerCount(stayHidden, stayAwake) 已被棄用。現在當頁面擷取完成時,會由 webContents.capturePage 自動處理。

const w = new BrowserWindow({ show: false })

// Removed in Electron 23
w.webContents.incrementCapturerCount()
w.capturePage().then(image => {
console.log(image.toDataURL())
w.webContents.decrementCapturerCount()
})

// Replace with
w.capturePage().then(image => {
console.log(image.toDataURL())
})

已棄用:webContents.decrementCapturerCount(stayHidden, stayAwake)

webContents.decrementCapturerCount(stayHidden, stayAwake) 已被棄用。現在當頁面擷取完成時,會由 webContents.capturePage 自動處理。

const w = new BrowserWindow({ show: false })

// Removed in Electron 23
w.webContents.incrementCapturerCount()
w.capturePage().then(image => {
console.log(image.toDataURL())
w.webContents.decrementCapturerCount()
})

// Replace with
w.capturePage().then(image => {
console.log(image.toDataURL())
})

已移除:WebContents 的 new-window 事件

WebContents 的 new-window 事件已被移除。它已被 webContents.setWindowOpenHandler() 取代。

// Removed in Electron 22
webContents.on('new-window', (event) => {
event.preventDefault()
})

// Replace with
webContents.setWindowOpenHandler((details) => {
return { action: 'deny' }
})

已移除:<webview>new-window 事件

<webview>new-window 事件已被移除。沒有直接的替代方案。

// Removed in Electron 22
webview.addEventListener('new-window', (event) => {})
// Replace with

// main.js
mainWindow.webContents.on('did-attach-webview', (event, wc) => {
wc.setWindowOpenHandler((details) => {
mainWindow.webContents.send('webview-new-window', wc.id, details)
return { action: 'deny' }
})
})

// preload.js
const { ipcRenderer } = require('electron')
ipcRenderer.on('webview-new-window', (e, webContentsId, details) => {
console.log('webview-new-window', webContentsId, details)
document.getElementById('webview').dispatchEvent(new Event('new-window'))
})

// renderer.js
document.getElementById('webview').addEventListener('new-window', () => {
console.log('got new-window event')
})

已棄用:BrowserWindow 的 scroll-touch-* 事件

BrowserWindow 上的 scroll-touch-beginscroll-touch-endscroll-touch-edge 事件已被棄用。請改用 WebContents 上新提供的 input-event 事件

// Deprecated
win.on('scroll-touch-begin', scrollTouchBegin)
win.on('scroll-touch-edge', scrollTouchEdge)
win.on('scroll-touch-end', scrollTouchEnd)

// Replace with
win.webContents.on('input-event', (_, event) => {
if (event.type === 'gestureScrollBegin') {
scrollTouchBegin()
} else if (event.type === 'gestureScrollUpdate') {
scrollTouchEdge()
} else if (event.type === 'gestureScrollEnd') {
scrollTouchEnd()
}
})

計畫性重大 API 變更 (21.0)

行為已變更:已啟用 V8 記憶體隔離區

已啟用 V8 記憶體隔離區,這會對使用 ArrayBufferBuffer 包裝非 V8 記憶體的原生模組產生影響。請參閱關於 V8 記憶體隔離區的部落格文章,以了解更多詳細資訊。

API 已變更:webContents.printToPDF()

webContents.printToPDF() 已被修改為符合 Chrome DevTools Protocol 中的 Page.printToPDF。 進行這些變更,是為了處理上游變更,這些變更使得我們先前的實作難以維護且錯誤百出。

已變更的參數

  • pageRanges

已移除的參數

  • printSelectionOnly
  • marginsType
  • headerFooter
  • scaleFactor

已新增的參數

  • headerTemplate
  • footerTemplate
  • displayHeaderFooter
  • margins
  • scale
  • preferCSSPageSize
// Main process
const { webContents } = require('electron')

webContents.printToPDF({
landscape: true,
displayHeaderFooter: true,
printBackground: true,
scale: 2,
pageSize: 'Ledger',
margins: {
top: 2,
bottom: 2,
left: 2,
right: 2
},
pageRanges: '1-5, 8, 11-13',
headerTemplate: '<h1>Title</h1>',
footerTemplate: '<div><span class="pageNumber"></span></div>',
preferCSSPageSize: true
}).then(data => {
fs.writeFile(pdfPath, data, (error) => {
if (error) throw error
console.log(`Wrote PDF successfully to ${pdfPath}`)
})
}).catch(error => {
console.log(`Failed to write PDF to ${pdfPath}: `, error)
})

計畫性重大 API 變更 (20.0)

已移除:macOS 10.11 / 10.12 支援

macOS 10.11 (El Capitan) 和 macOS 10.12 (Sierra) 已不再受 Chromium 支援。

舊版的 Electron 將繼續在這些作業系統上執行,但執行 Electron v20.0.0 及更高版本需要 macOS 10.13 (High Sierra) 或更高版本。

預設值已變更:未指定 nodeIntegration: true 的渲染器預設為沙箱化

先前,指定了預載腳本的渲染器預設為非沙箱化。這表示預設情況下,預載腳本可以存取 Node.js。在 Electron 20 中,此預設值已變更。從 Electron 20 開始,渲染器預設為沙箱化,除非指定了 nodeIntegration: truesandbox: false

如果您的預載腳本不依賴 Node,則無需採取任何動作。如果您的預載腳本確實依賴 Node,請重構它們以移除渲染器中的 Node 使用,或明確地為相關的渲染器指定 sandbox: false

已移除:Linux 上的 skipTaskbar

在 X11 上,skipTaskbar 會向 X11 視窗管理器傳送 _NET_WM_STATE_SKIP_TASKBAR 訊息。Wayland 沒有直接的等效項目,而已知的工作區變通方案具有無法接受的權衡 (例如,GNOME 中的 Window.is_skip_taskbar 需要不安全模式),因此 Electron 無法在 Linux 上支援此功能。

API 已變更:session.setDevicePermissionHandler(handler)

當使用 session.setDevicePermissionHandler(handler) 時呼叫的處理函式,其引數已變更。此處理函式不再傳遞框架 WebFrameMain,而是傳遞 origin,這是正在檢查裝置權限的來源。

計畫性重大 API 變更 (19.0)

已移除:IA32 Linux 二進位檔

這是因為 Chromium 102.0.4999.0 已停止支援 IA32 Linux。這結束了移除對 IA32 Linux 的支援

計畫性重大 API 變更 (18.0)

已移除:nativeWindowOpen

在 Electron 15 之前,預設情況下會對 window.open 進行墊片處理以使用 BrowserWindowProxy。這表示 window.open('about:blank') 無法開啟同步可編寫腳本的子視窗,以及其他不相容性。自 Electron 15 起,預設已啟用 nativeWindowOpen

請參閱Electron 中 window.open 的文件,以了解更多詳細資訊。

計畫性重大 API 變更 (17.0)

已移除:渲染器中的 desktopCapturer.getSources

desktopCapturer.getSources API 現在僅在主處理程序中可用。此變更是為了提高 Electron 應用程式的預設安全性。

如果您需要此功能,可以透過以下方式取代

// Main process
const { ipcMain, desktopCapturer } = require('electron')

ipcMain.handle(
'DESKTOP_CAPTURER_GET_SOURCES',
(event, opts) => desktopCapturer.getSources(opts)
)
// Renderer process
const { ipcRenderer } = require('electron')

const desktopCapturer = {
getSources: (opts) => ipcRenderer.invoke('DESKTOP_CAPTURER_GET_SOURCES', opts)
}

但是,您應該考慮進一步限制傳回給渲染器的資訊;例如,向使用者顯示來源選取器,並僅傳回選取的來源。

已棄用:nativeWindowOpen

在 Electron 15 之前,預設情況下會對 window.open 進行墊片處理以使用 BrowserWindowProxy。這表示 window.open('about:blank') 無法開啟同步可編寫腳本的子視窗,以及其他不相容性。自 Electron 15 起,預設已啟用 nativeWindowOpen

請參閱Electron 中 window.open 的文件,以了解更多詳細資訊。

計畫性重大 API 變更 (16.0)

行為已變更:Linux 上的 crashReporter 實作已切換為 Crashpad

Linux 上 crashReporter API 的底層實作已從 Breakpad 變更為 Crashpad,使其與 Windows 和 Mac 一致。因此,現在會自動監控子處理程序,並且不再需要在 Node 子處理程序中呼叫 process.crashReporter.start (也不建議這樣做,因為它會啟動第二個 Crashpad 報告程式執行個體)。

Linux 上回報註釋的方式也有些微變更,包括長值將不再在以 __1__2 等附加的註釋之間分割,而是會在 (新的、更長的) 註釋值限制處截斷。

已棄用:渲染器中的 desktopCapturer.getSources

已棄用在渲染器中使用 desktopCapturer.getSources API,且將被移除。此變更改善了 Electron 應用程式的預設安全性。

請參閱這裡,以了解如何在您的應用程式中取代此 API。

計畫性重大 API 變更 (15.0)

預設值已變更:nativeWindowOpen 預設為 true

在 Electron 15 之前,window.open 預設會被墊片(shim)處理,改用 BrowserWindowProxy。這意味著 window.open('about:blank') 無法同步開啟可使用腳本操作的子視窗,以及其他的不相容性。nativeWindowOpen 已不再是實驗性的功能,現在是預設行為。

請參閱Electron 中 window.open 的文件,以了解更多詳細資訊。

已棄用:app.runningUnderRosettaTranslation

app.runningUnderRosettaTranslation 屬性已被棄用。請改用 app.runningUnderARM64Translation

// Deprecated
console.log(app.runningUnderRosettaTranslation)
// Replace with
console.log(app.runningUnderARM64Translation)

計畫中的重大 API 變更(14.0)

已移除:remote 模組

remote 模組已在 Electron 12 中被棄用,並將在 Electron 14 中移除。它已被 @electron/remote 模組取代。

// Deprecated in Electron 12:
const { BrowserWindow } = require('electron').remote
// Replace with:
const { BrowserWindow } = require('@electron/remote')

// In the main process:
require('@electron/remote/main').initialize()

已移除:app.allowRendererProcessReuse

app.allowRendererProcessReuse 屬性將被移除,這是為了更密切地與 Chromium 的進程模型對齊,以確保安全性、效能和可維護性。

如需更詳細的資訊,請參閱 #18397

已移除:瀏覽器視窗關聯性(Browser Window Affinity)

建構新的 BrowserWindow 時的 affinity 選項將被移除,這是為了更密切地與 Chromium 的進程模型對齊,以確保安全性、效能和可維護性。

如需更詳細的資訊,請參閱 #18397

API 已變更:window.open()

選用的參數 frameName 將不再設定視窗的標題。現在它遵循 原生文件 中對應參數 windowName 的規範。

如果您使用此參數來設定視窗的標題,您可以改用 win.setTitle(title)

已移除:worldSafeExecuteJavaScript

在 Electron 14 中,worldSafeExecuteJavaScript 將被移除。沒有替代方案,請確保您的程式碼在此屬性啟用時可以正常運作。自 Electron 12 以來,它已預設啟用。

如果您使用 webFrame.executeJavaScriptwebFrame.executeJavaScriptInIsolatedWorld,您將會受到此變更的影響。您需要確保這些方法傳回的值受到 Context Bridge API 的支援,因為這些方法使用相同的數值傳遞語意。

已移除:BrowserWindowConstructorOptions 從父視窗繼承

在 Electron 14 之前,使用 window.open 開啟的視窗會從其父視窗繼承 BrowserWindow 建構函式選項,例如 transparentresizable。從 Electron 14 開始,此行為已移除,視窗將不會從其父視窗繼承任何 BrowserWindow 建構函式選項。

請改用 setWindowOpenHandler 來明確設定新視窗的選項。

webContents.setWindowOpenHandler((details) => {
return {
action: 'allow',
overrideBrowserWindowOptions: {
// ...
}
}
})

已移除:additionalFeatures

WebContents 的 new-windowdid-create-window 事件中已棄用的 additionalFeatures 屬性已被移除。由於 new-window 使用位置參數,該參數仍然存在,但始終會是空陣列 []。(請注意,new-window 事件本身已被棄用,並由 setWindowOpenHandler 取代。)視窗功能中的裸鍵現在將在選項物件中呈現為值為 true 的鍵。

// Removed in Electron 14
// Triggered by window.open('...', '', 'my-key')
webContents.on('did-create-window', (window, details) => {
if (details.additionalFeatures.includes('my-key')) {
// ...
}
})

// Replace with
webContents.on('did-create-window', (window, details) => {
if (details.options['my-key']) {
// ...
}
})

計畫中的重大 API 變更(13.0)

API 已變更:session.setPermissionCheckHandler(handler)

handler 方法的第一個參數以前始終是 webContents,現在有時可能是 null。您應該使用 requestingOriginembeddingOriginsecurityOrigin 屬性來正確回應權限檢查。由於 webContents 可以是 null,因此不能再依賴它。

// Old code
session.setPermissionCheckHandler((webContents, permission) => {
if (webContents.getURL().startsWith('https://google.com/') && permission === 'notification') {
return true
}
return false
})

// Replace with
session.setPermissionCheckHandler((webContents, permission, requestingOrigin) => {
if (new URL(requestingOrigin).hostname === 'google.com' && permission === 'notification') {
return true
}
return false
})

已移除:shell.moveItemToTrash()

已棄用的同步 shell.moveItemToTrash() API 已被移除。請改用非同步的 shell.trashItem()

// Removed in Electron 13
shell.moveItemToTrash(path)
// Replace with
shell.trashItem(path).then(/* ... */)

已移除:BrowserWindow 擴充功能 API

已棄用的擴充功能 API 已被移除

  • BrowserWindow.addExtension(path)
  • BrowserWindow.addDevToolsExtension(path)
  • BrowserWindow.removeExtension(name)
  • BrowserWindow.removeDevToolsExtension(name)
  • BrowserWindow.getExtensions()
  • BrowserWindow.getDevToolsExtensions()

請改用 session API

  • ses.loadExtension(path)
  • ses.removeExtension(extension_id)
  • ses.getAllExtensions()
// Removed in Electron 13
BrowserWindow.addExtension(path)
BrowserWindow.addDevToolsExtension(path)
// Replace with
session.defaultSession.loadExtension(path)
// Removed in Electron 13
BrowserWindow.removeExtension(name)
BrowserWindow.removeDevToolsExtension(name)
// Replace with
session.defaultSession.removeExtension(extension_id)
// Removed in Electron 13
BrowserWindow.getExtensions()
BrowserWindow.getDevToolsExtensions()
// Replace with
session.defaultSession.getAllExtensions()

已移除:systemPreferences 中的方法

以下 systemPreferences 方法已棄用

  • systemPreferences.isDarkMode()
  • systemPreferences.isInvertedColorScheme()
  • systemPreferences.isHighContrastColorScheme()

請改用以下 nativeTheme 屬性

  • nativeTheme.shouldUseDarkColors
  • nativeTheme.shouldUseInvertedColorScheme
  • nativeTheme.shouldUseHighContrastColors
// Removed in Electron 13
systemPreferences.isDarkMode()
// Replace with
nativeTheme.shouldUseDarkColors

// Removed in Electron 13
systemPreferences.isInvertedColorScheme()
// Replace with
nativeTheme.shouldUseInvertedColorScheme

// Removed in Electron 13
systemPreferences.isHighContrastColorScheme()
// Replace with
nativeTheme.shouldUseHighContrastColors

已棄用:WebContents 的 new-window 事件

WebContents 的 new-window 事件已被棄用。它已被 webContents.setWindowOpenHandler() 取代。

// Deprecated in Electron 13
webContents.on('new-window', (event) => {
event.preventDefault()
})

// Replace with
webContents.setWindowOpenHandler((details) => {
return { action: 'deny' }
})

計畫中的重大 API 變更(12.0)

已移除:Pepper Flash 支援

Chromium 已移除對 Flash 的支援,因此我們必須跟進。如需更多詳細資訊,請參閱 Chromium 的 Flash Roadmap

預設已變更:worldSafeExecuteJavaScript 預設為 true

在 Electron 12 中,worldSafeExecuteJavaScript 將預設啟用。若要恢復先前的行為,必須在 WebPreferences 中指定 worldSafeExecuteJavaScript: false。請注意,將此選項設為 false 是**不安全**的。

此選項將在 Electron 14 中移除,因此請遷移您的程式碼以支援預設值。

預設已變更:contextIsolation 預設為 true

在 Electron 12 中,contextIsolation 將預設啟用。若要恢復先前的行為,必須在 WebPreferences 中指定 contextIsolation: false

我們建議啟用 contextIsolation 以確保您的應用程式的安全性。

另一個影響是,除非 nodeIntegrationtruecontextIsolationfalse,否則無法在渲染器進程中使用 require()

如需更多詳細資訊,請參閱:https://github.com/electron/electron/issues/23506

已移除:crashReporter.getCrashesDirectory()

crashReporter.getCrashesDirectory 方法已移除。應使用 app.getPath('crashDumps') 取代。

// Removed in Electron 12
crashReporter.getCrashesDirectory()
// Replace with
app.getPath('crashDumps')

已移除:渲染器進程中的 crashReporter 方法

以下 crashReporter 方法不再在渲染器進程中可用

  • crashReporter.start
  • crashReporter.getLastCrashReport
  • crashReporter.getUploadedReports
  • crashReporter.getUploadToServer
  • crashReporter.setUploadToServer
  • crashReporter.getCrashesDirectory

它們應該只從主進程呼叫。

如需更多詳細資訊,請參閱 #23265

預設已變更:crashReporter.start({ compress: true })

crashReporter.startcompress 選項的預設值已從 false 變更為 true。這表示損毀傾印將以 Content-Encoding: gzip 標頭上傳到損毀接收伺服器,並且主體將會壓縮。

如果您的損毀接收伺服器不支援壓縮的有效負載,您可以在損毀回報器選項中指定 { compress: false } 來關閉壓縮。

已棄用:remote 模組

remote 模組在 Electron 12 中已棄用,並將在 Electron 14 中移除。它已被 @electron/remote 模組取代。

// Deprecated in Electron 12:
const { BrowserWindow } = require('electron').remote
// Replace with:
const { BrowserWindow } = require('@electron/remote')

// In the main process:
require('@electron/remote/main').initialize()

已棄用:shell.moveItemToTrash()

同步的 shell.moveItemToTrash() 已被新的非同步 shell.trashItem() 取代。

// Deprecated in Electron 12
shell.moveItemToTrash(path)
// Replace with
shell.trashItem(path).then(/* ... */)

計畫中的重大 API 變更(11.0)

已移除:BrowserView.{destroy, fromId, fromWebContents, getAllViews}BrowserViewid 屬性

實驗性的 API BrowserView.{destroy, fromId, fromWebContents, getAllViews} 現已移除。此外,BrowserViewid 屬性也已移除。

如需更詳細的資訊,請參閱 #23578

計畫性重大 API 變更 (10.0)

已棄用:crashReporter.start()companyName 參數

crashReporter.start()companyName 參數,先前為必要參數,現在改為選用參數,並且已被棄用。若要以非棄用的方式達到相同的行為,您可以在 globalExtra 中傳遞 companyName 值。

// Deprecated in Electron 10
crashReporter.start({ companyName: 'Umbrella Corporation' })
// Replace with
crashReporter.start({ globalExtra: { _companyName: 'Umbrella Corporation' } })

已棄用:crashReporter.getCrashesDirectory()

crashReporter.getCrashesDirectory 方法已被棄用。應使用 app.getPath('crashDumps') 來取代。

// Deprecated in Electron 10
crashReporter.getCrashesDirectory()
// Replace with
app.getPath('crashDumps')

已棄用:渲染器進程中的 crashReporter 方法

從渲染器進程呼叫以下 crashReporter 方法已被棄用

  • crashReporter.start
  • crashReporter.getLastCrashReport
  • crashReporter.getUploadedReports
  • crashReporter.getUploadToServer
  • crashReporter.setUploadToServer
  • crashReporter.getCrashesDirectory

渲染器中 crashReporter 模組中唯一保留且未棄用的方法為 addExtraParameterremoveExtraParametergetParameters

從主進程呼叫時,以上所有方法均保持未棄用。

如需更多詳細資訊,請參閱 #23265

已棄用:crashReporter.start({ compress: false })

crashReporter.start 中設定 { compress: false } 已被棄用。幾乎所有的損毀收集伺服器都支援 gzip 壓縮。此選項將在未來版本的 Electron 中移除。

預設值已變更:enableRemoteModule 預設為 false

在 Electron 9 中,若未使用 enableRemoteModule WebPreferences 選項明確啟用 remote 模組,則會開始發出警告。在 Electron 10 中,remote 模組預設為停用。若要使用 remote 模組,必須在 WebPreferences 中指定 enableRemoteModule: true

const w = new BrowserWindow({
webPreferences: {
enableRemoteModule: true
}
})

我們建議您停止使用 remote 模組

protocol.unregisterProtocol

protocol.uninterceptProtocol

這些 API 現在為同步的,不再需要選用的回呼。

// Deprecated
protocol.unregisterProtocol(scheme, () => { /* ... */ })
// Replace with
protocol.unregisterProtocol(scheme)

protocol.registerFileProtocol

protocol.registerBufferProtocol

protocol.registerStringProtocol

protocol.registerHttpProtocol

protocol.registerStreamProtocol

protocol.interceptFileProtocol

protocol.interceptStringProtocol

protocol.interceptBufferProtocol

protocol.interceptHttpProtocol

protocol.interceptStreamProtocol

這些 API 現在為同步的,不再需要選用的回呼。

// Deprecated
protocol.registerFileProtocol(scheme, handler, () => { /* ... */ })
// Replace with
protocol.registerFileProtocol(scheme, handler)

已註冊或攔截的協定在發生導覽之前不會對目前頁面產生影響。

protocol.isProtocolHandled

此 API 已被棄用,使用者應改用 protocol.isProtocolRegisteredprotocol.isProtocolIntercepted

// Deprecated
protocol.isProtocolHandled(scheme).then(() => { /* ... */ })
// Replace with
const isRegistered = protocol.isProtocolRegistered(scheme)
const isIntercepted = protocol.isProtocolIntercepted(scheme)

計畫性重大 API 變更 (9.0)

預設值已變更:預設為停用在渲染器進程中載入非內容感知的原生模組

從 Electron 9 開始,我們不允許在渲染器進程中載入非內容感知的原生模組。這是為了提高 Electron 作為專案的安全性、效能和可維護性。

如果這影響到您,您可以暫時將 app.allowRendererProcessReuse 設定為 false 以恢復為舊行為。此旗標將只在 Electron 11 之前有效,因此您應該計劃更新您的原生模組以使其具備內容感知能力。

如需更詳細的資訊,請參閱 #18397

已棄用:BrowserWindow 擴充 API

以下擴充 API 已被棄用

  • BrowserWindow.addExtension(path)
  • BrowserWindow.addDevToolsExtension(path)
  • BrowserWindow.removeExtension(name)
  • BrowserWindow.removeDevToolsExtension(name)
  • BrowserWindow.getExtensions()
  • BrowserWindow.getDevToolsExtensions()

請改用 session API

  • ses.loadExtension(path)
  • ses.removeExtension(extension_id)
  • ses.getAllExtensions()
// Deprecated in Electron 9
BrowserWindow.addExtension(path)
BrowserWindow.addDevToolsExtension(path)
// Replace with
session.defaultSession.loadExtension(path)
// Deprecated in Electron 9
BrowserWindow.removeExtension(name)
BrowserWindow.removeDevToolsExtension(name)
// Replace with
session.defaultSession.removeExtension(extension_id)
// Deprecated in Electron 9
BrowserWindow.getExtensions()
BrowserWindow.getDevToolsExtensions()
// Replace with
session.defaultSession.getAllExtensions()

已移除:<webview>.getWebContents()

此 API 已在 Electron 8.0 中棄用,現在已移除。

// Removed in Electron 9.0
webview.getWebContents()
// Replace with
const { remote } = require('electron')
remote.webContents.fromId(webview.getWebContentsId())

已移除:webFrame.setLayoutZoomLevelLimits()

Chromium 已移除對變更版面縮放比例限制的支援,這已超出 Electron 的維護能力範圍。該函式已在 Electron 8.x 中棄用,並在 Electron 9.x 中移除。版面縮放比例限制現在固定為最小 0.25 和最大 5.0,如此處所定義。

行為變更:透過 IPC 發送非 JS 物件現在會拋出例外

在 Electron 8.0 中,IPC 已變更為使用結構化複製演算法,帶來了顯著的效能提升。為了簡化轉換,保留了舊的 IPC 序列化演算法,並將其用於某些無法使用結構化複製序列化的物件。特別是,DOM 物件(例如 ElementLocationDOMMatrix)、由 C++ 類別支援的 Node.js 物件(例如 process.envStream 的某些成員)以及由 C++ 類別支援的 Electron 物件(例如 WebContentsBrowserWindowWebFrame)都無法使用結構化複製序列化。每當調用舊演算法時,都會印出棄用警告。

在 Electron 9.0 中,舊的序列化演算法已移除,並且發送此類無法序列化的物件現在將會拋出「無法複製物件」錯誤。

API 變更:shell.openItem 現在為 shell.openPath

shell.openItem API 已被非同步的 shell.openPath API 取代。您可以在此處查看原始的 API 提案和原因。

計畫性重大 API 變更 (8.0)

行為變更:透過 IPC 發送的值現在使用結構化複製演算法序列化

用於序列化透過 IPC 發送的物件(透過 ipcRenderer.sendipcRenderer.sendSyncWebContents.send 和相關方法)的演算法已從自訂演算法切換為 V8 內建的結構化複製演算法,與用於序列化 postMessage 的訊息的演算法相同。這為大型訊息帶來了 2 倍的效能提升,但也帶來了一些行為上的重大變更。

  • 透過 IPC 發送函式、Promise、WeakMap、WeakSet 或包含任何此類值的物件現在將會拋出例外,而不是靜默地將函式轉換為 undefined
// Previously:
ipcRenderer.send('channel', { value: 3, someFunction: () => {} })
// => results in { value: 3 } arriving in the main process

// From Electron 8:
ipcRenderer.send('channel', { value: 3, someFunction: () => {} })
// => throws Error("() => {} could not be cloned.")
  • NaNInfinity-Infinity 現在將會正確序列化,而不是轉換為 null
  • 包含循環參考的物件現在將會正確序列化,而不是轉換為 null
  • SetMapErrorRegExp 的值將會被正確序列化,而不會被轉換成 {}
  • BigInt 的值將會被正確序列化,而不會被轉換成 null
  • 稀疏陣列將會以其原樣序列化,而不會被轉換成包含 null 的密集陣列。
  • Date 物件將會以 Date 物件的形式傳輸,而不會被轉換成 ISO 字串表示法。
  • 類型陣列(例如 Uint8ArrayUint16ArrayUint32Array 等)將會以其原樣傳輸,而不會被轉換成 Node.js 的 Buffer
  • Node.js 的 Buffer 物件將會以 Uint8Array 的形式傳輸。您可以將 Uint8Array 包裝在底層的 ArrayBuffer 中,將其轉換回 Node.js 的 Buffer
Buffer.from(value.buffer, value.byteOffset, value.byteLength)

傳送任何非原生 JS 型別的物件,例如 DOM 物件(例如 ElementLocationDOMMatrix)、Node.js 物件(例如 process.envStream)或 Electron 物件(例如 WebContentsBrowserWindowWebFrame)已被棄用。在 Electron 8 中,這些物件將會像以前一樣被序列化,並帶有 DeprecationWarning 訊息,但從 Electron 9 開始,傳送這些類型的物件將會拋出「無法複製」的錯誤。

已棄用:<webview>.getWebContents()

此 API 是使用 remote 模組實作的,這會帶來效能和安全性方面的影響。因此,其使用應明確指定。

// Deprecated
webview.getWebContents()
// Replace with
const { remote } = require('electron')
remote.webContents.fromId(webview.getWebContentsId())

然而,建議完全避免使用 remote 模組。

// main
const { ipcMain, webContents } = require('electron')

const getGuestForWebContents = (webContentsId, contents) => {
const guest = webContents.fromId(webContentsId)
if (!guest) {
throw new Error(`Invalid webContentsId: ${webContentsId}`)
}
if (guest.hostWebContents !== contents) {
throw new Error('Access denied to webContents')
}
return guest
}

ipcMain.handle('openDevTools', (event, webContentsId) => {
const guest = getGuestForWebContents(webContentsId, event.sender)
guest.openDevTools()
})

// renderer
const { ipcRenderer } = require('electron')

ipcRenderer.invoke('openDevTools', webview.getWebContentsId())

已棄用:webFrame.setLayoutZoomLevelLimits()

Chromium 已移除變更版面縮放比例限制的支援,並且 Electron 無法維護此功能。該函式將會在 Electron 8.x 中發出警告,並在 Electron 9.x 中停止存在。版面縮放比例限制現在固定在最小值 0.25 和最大值 5.0,如此處所定義。

systemPreferences 中已棄用的事件

以下 systemPreferences 事件已被棄用

  • inverted-color-scheme-changed
  • high-contrast-color-scheme-changed

請改用 nativeTheme 模組上的新 updated 事件。

// Deprecated
systemPreferences.on('inverted-color-scheme-changed', () => { /* ... */ })
systemPreferences.on('high-contrast-color-scheme-changed', () => { /* ... */ })

// Replace with
nativeTheme.on('updated', () => { /* ... */ })

已棄用:systemPreferences 中的方法

以下 systemPreferences 方法已棄用

  • systemPreferences.isDarkMode()
  • systemPreferences.isInvertedColorScheme()
  • systemPreferences.isHighContrastColorScheme()

請改用以下 nativeTheme 屬性

  • nativeTheme.shouldUseDarkColors
  • nativeTheme.shouldUseInvertedColorScheme
  • nativeTheme.shouldUseHighContrastColors
// Deprecated
systemPreferences.isDarkMode()
// Replace with
nativeTheme.shouldUseDarkColors

// Deprecated
systemPreferences.isInvertedColorScheme()
// Replace with
nativeTheme.shouldUseInvertedColorScheme

// Deprecated
systemPreferences.isHighContrastColorScheme()
// Replace with
nativeTheme.shouldUseHighContrastColors

計畫中的重大 API 變更 (7.0)

已棄用:Atom.io Node 標頭 URL

這是當建置原生 Node 模組時,在 .npmrc 檔案中指定為 disturl 或作為 --dist-url 命令列旗標的 URL。這兩者在可預見的未來都將受到支援,但建議您切換。

已棄用:https://atom.io/download/electron

替換為:https://electron.dev.org.tw/headers

API 已變更:session.clearAuthCache() 不再接受選項

session.clearAuthCache API 不再接受要清除的選項,而是無條件地清除整個快取。

// Deprecated
session.clearAuthCache({ type: 'password' })
// Replace with
session.clearAuthCache()

API 已變更:powerMonitor.querySystemIdleState 現在為 powerMonitor.getSystemIdleState

// Removed in Electron 7.0
powerMonitor.querySystemIdleState(threshold, callback)
// Replace with synchronous API
const idleState = powerMonitor.getSystemIdleState(threshold)

API 已變更:powerMonitor.querySystemIdleTime 現在為 powerMonitor.getSystemIdleTime

// Removed in Electron 7.0
powerMonitor.querySystemIdleTime(callback)
// Replace with synchronous API
const idleTime = powerMonitor.getSystemIdleTime()

API 已變更:webFrame.setIsolatedWorldInfo 取代了個別方法

// Removed in Electron 7.0
webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp)
webFrame.setIsolatedWorldHumanReadableName(worldId, name)
webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin)
// Replace with
webFrame.setIsolatedWorldInfo(
worldId,
{
securityOrigin: 'some_origin',
name: 'human_readable_name',
csp: 'content_security_policy'
})

已移除:getBlinkMemoryInfo 上的 marked 屬性

此屬性已在 Chromium 77 中移除,因此不再可用。

行為已變更:<input type="file"/>webkitdirectory 屬性現在會列出目錄內容

HTML 檔案輸入上的 webkitdirectory 屬性允許選擇資料夾。先前版本的 Electron 有不正確的實作,輸入的 event.target.files 會回傳一個 FileList,該 FileList 會回傳對應於所選資料夾的一個 File

從 Electron 7 開始,該 FileList 現在會列出資料夾中包含的所有檔案,類似於 Chrome、Firefox 和 Edge(連結到 MDN 文件)。

舉例來說,假設有一個資料夾具有以下結構

folder
├── file1
├── file2
└── file3

在 Electron <=6 中,這會回傳一個 FileList,其中包含一個用於

path/to/folder

在 Electron 7 中,這現在會回傳一個 FileList,其中包含一個用於

/path/to/folder/file3
/path/to/folder/file2
/path/to/folder/file1

請注意,webkitdirectory 不再公開所選資料夾的路徑。如果您需要所選資料夾的路徑,而不是資料夾內容,請參閱 dialog.showOpenDialog API(連結)。

API 已變更:基於回呼的已 Promise 化 API 版本

Electron 5 和 Electron 6 引入了現有非同步 API 的基於 Promise 的版本,並棄用了較舊的基於回呼的對應版本。在 Electron 7 中,所有已棄用的基於回呼的 API 現在都已移除。

這些函式現在只會回傳 Promise

  • app.getFileIcon() #15742
  • app.dock.show() #16904
  • contentTracing.getCategories() #16583
  • contentTracing.getTraceBufferUsage() #16600
  • contentTracing.startRecording() #16584
  • contentTracing.stopRecording() #16584
  • contents.executeJavaScript() #17312
  • cookies.flushStore() #16464
  • cookies.get() #16464
  • cookies.remove() #16464
  • cookies.set() #16464
  • debugger.sendCommand() #16861
  • dialog.showCertificateTrustDialog() #17181
  • inAppPurchase.getProducts() #17355
  • inAppPurchase.purchaseProduct()#17355
  • netLog.stopLogging() #16862
  • session.clearAuthCache() #17259
  • session.clearCache() #17185
  • session.clearHostResolverCache() #17229
  • session.clearStorageData() #17249
  • session.getBlobData() #17303
  • session.getCacheSize() #17185
  • session.resolveProxy() #17222
  • session.setProxy() #17222
  • shell.openExternal() #16176
  • webContents.loadFile() #15855
  • webContents.loadURL() #15855
  • webContents.hasServiceWorker() #16535
  • webContents.printToPDF() #16795
  • webContents.savePage() #16742
  • webFrame.executeJavaScript() #17312
  • webFrame.executeJavaScriptInIsolatedWorld() #17312
  • webviewTag.executeJavaScript() #17312
  • win.capturePage() #15743

這些函式現在有兩種形式,同步和基於 Promise 的非同步

  • dialog.showMessageBox()/dialog.showMessageBoxSync() #17298
  • dialog.showOpenDialog()/dialog.showOpenDialogSync() #16973
  • dialog.showSaveDialog()/dialog.showSaveDialogSync() #17054

計畫中的重大 API 變更 (6.0)

API 已變更:win.setMenu(null) 現在為 win.removeMenu()

// Deprecated
win.setMenu(null)
// Replace with
win.removeMenu()

API 已變更:應該透過 remote 存取渲染程序中的 electron.screen

// Deprecated
require('electron').screen
// Replace with
require('electron').remote.screen

API 已變更:在沙箱渲染器中 require() Node 內建物件不再隱含地載入 remote 版本

// Deprecated
require('child_process')
// Replace with
require('electron').remote.require('child_process')

// Deprecated
require('fs')
// Replace with
require('electron').remote.require('fs')

// Deprecated
require('os')
// Replace with
require('electron').remote.require('os')

// Deprecated
require('path')
// Replace with
require('electron').remote.require('path')

已棄用:powerMonitor.querySystemIdleState 已被 powerMonitor.getSystemIdleState 取代

// Deprecated
powerMonitor.querySystemIdleState(threshold, callback)
// Replace with synchronous API
const idleState = powerMonitor.getSystemIdleState(threshold)

已棄用:powerMonitor.querySystemIdleTime 已被 powerMonitor.getSystemIdleTime 取代

// Deprecated
powerMonitor.querySystemIdleTime(callback)
// Replace with synchronous API
const idleTime = powerMonitor.getSystemIdleTime()

已棄用:不再需要 app.enableMixedSandbox()

// Deprecated
app.enableMixedSandbox()

混合沙盒模式現在預設為啟用。

已棄用:Tray.setHighlightMode

在 macOS Catalina 下,我們之前的 Tray 實作會失效。Apple 的原生替代方案不支援變更醒目提示行為。

// Deprecated
tray.setHighlightMode(mode)
// API will be removed in v7.0 without replacement.

計畫中的重大 API 變更 (5.0)

預設值已變更:nodeIntegrationwebviewTag 預設為 false,contextIsolation 預設為 true

以下 webPreferences 選項的預設值已棄用,改用以下列出的新預設值。

屬性已棄用的預設值新的預設值
contextIsolationfalsetrue
nodeIntegrationtruefalse
webviewTag如果已設定 nodeIntegration 則為 nodeIntegration,否則為 truefalse

例如,重新啟用 webviewTag

const w = new BrowserWindow({
webPreferences: {
webviewTag: true
}
})

行為已變更:透過 nativeWindowOpen 開啟的子視窗中的 nodeIntegration

除非 nodeIntegrationInSubFramestrue,否則使用 nativeWindowOpen 選項開啟的子視窗將永遠停用 Node.js 整合。

API 已變更:註冊特權協定現在必須在應用程式準備好之前完成

渲染器處理程序 API webFrame.registerURLSchemeAsPrivilegedwebFrame.registerURLSchemeAsBypassingCSP 以及瀏覽器處理程序 API protocol.registerStandardSchemes 已被移除。新增了一個新的 API protocol.registerSchemesAsPrivileged,應該用於註冊具有所需特權的自訂協定。自訂協定必須在應用程式準備好之前註冊。

已棄用:webFrame.setIsolatedWorld* 已被 webFrame.setIsolatedWorldInfo 取代

// Deprecated
webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp)
webFrame.setIsolatedWorldHumanReadableName(worldId, name)
webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin)
// Replace with
webFrame.setIsolatedWorldInfo(
worldId,
{
securityOrigin: 'some_origin',
name: 'human_readable_name',
csp: 'content_security_policy'
})

API 已變更:webFrame.setSpellCheckProvider 現在接受非同步回呼

spellCheck 回呼現在是非同步的,並且已移除 autoCorrectWord 參數。

// Deprecated
webFrame.setSpellCheckProvider('en-US', true, {
spellCheck: (text) => {
return !spellchecker.isMisspelled(text)
}
})
// Replace with
webFrame.setSpellCheckProvider('en-US', {
spellCheck: (words, callback) => {
callback(words.filter(text => spellchecker.isMisspelled(text)))
}
})

API 已變更:webContents.getZoomLevelwebContents.getZoomFactor 現在是同步的

webContents.getZoomLevelwebContents.getZoomFactor 不再需要回呼參數,而是直接傳回它們的數字值。

// Deprecated
webContents.getZoomLevel((level) => {
console.log(level)
})
// Replace with
const level = webContents.getZoomLevel()
console.log(level)
// Deprecated
webContents.getZoomFactor((factor) => {
console.log(factor)
})
// Replace with
const factor = webContents.getZoomFactor()
console.log(factor)

計畫中的重大 API 變更 (4.0)

以下清單包含 Electron 4.0 中所做的重大 API 變更。

app.makeSingleInstance

// Deprecated
app.makeSingleInstance((argv, cwd) => {
/* ... */
})
// Replace with
app.requestSingleInstanceLock()
app.on('second-instance', (event, argv, cwd) => {
/* ... */
})

app.releaseSingleInstance

// Deprecated
app.releaseSingleInstance()
// Replace with
app.releaseSingleInstanceLock()

app.getGPUInfo

app.getGPUInfo('complete')
// Now behaves the same with `basic` on macOS
app.getGPUInfo('basic')

win_delay_load_hook

在為 Windows 建置原生模組時,模組的 binding.gyp 中的 win_delay_load_hook 變數必須為 true (這是預設值)。如果不存在這個 hook,則原生模組將無法在 Windows 上載入,並出現類似 Cannot find module 的錯誤訊息。如需更多資訊,請參閱原生模組指南

已移除:IA32 Linux 支援

Electron 18 將不再在 32 位元 Linux 系統上執行。如需更多資訊,請參閱停止支援 32 位元 Linux

重大 API 變更 (3.0)

以下清單包含 Electron 3.0 中的重大 API 變更。

app

// Deprecated
app.getAppMemoryInfo()
// Replace with
app.getAppMetrics()

// Deprecated
const metrics = app.getAppMetrics()
const { memory } = metrics[0] // Deprecated property

BrowserWindow

// Deprecated
const optionsA = { webPreferences: { blinkFeatures: '' } }
const windowA = new BrowserWindow(optionsA)
// Replace with
const optionsB = { webPreferences: { enableBlinkFeatures: '' } }
const windowB = new BrowserWindow(optionsB)

// Deprecated
window.on('app-command', (e, cmd) => {
if (cmd === 'media-play_pause') {
// do something
}
})
// Replace with
window.on('app-command', (e, cmd) => {
if (cmd === 'media-play-pause') {
// do something
}
})

clipboard

// Deprecated
clipboard.readRtf()
// Replace with
clipboard.readRTF()

// Deprecated
clipboard.writeRtf()
// Replace with
clipboard.writeRTF()

// Deprecated
clipboard.readHtml()
// Replace with
clipboard.readHTML()

// Deprecated
clipboard.writeHtml()
// Replace with
clipboard.writeHTML()

crashReporter

// Deprecated
crashReporter.start({
companyName: 'Crashly',
submitURL: 'https://crash.server.com',
autoSubmit: true
})
// Replace with
crashReporter.start({
companyName: 'Crashly',
submitURL: 'https://crash.server.com',
uploadToServer: true
})

nativeImage

// Deprecated
nativeImage.createFromBuffer(buffer, 1.0)
// Replace with
nativeImage.createFromBuffer(buffer, {
scaleFactor: 1.0
})

process

// Deprecated
const info = process.getProcessMemoryInfo()

screen

// Deprecated
screen.getMenuBarHeight()
// Replace with
screen.getPrimaryDisplay().workArea

session

// Deprecated
ses.setCertificateVerifyProc((hostname, certificate, callback) => {
callback(true)
})
// Replace with
ses.setCertificateVerifyProc((request, callback) => {
callback(0)
})

Tray

// Deprecated
tray.setHighlightMode(true)
// Replace with
tray.setHighlightMode('on')

// Deprecated
tray.setHighlightMode(false)
// Replace with
tray.setHighlightMode('off')

webContents

// Deprecated
webContents.openDevTools({ detach: true })
// Replace with
webContents.openDevTools({ mode: 'detach' })

// Removed
webContents.setSize(options)
// There is no replacement for this API

webFrame

// Deprecated
webFrame.registerURLSchemeAsSecure('app')
// Replace with
protocol.registerStandardSchemes(['app'], { secure: true })

// Deprecated
webFrame.registerURLSchemeAsPrivileged('app', { secure: true })
// Replace with
protocol.registerStandardSchemes(['app'], { secure: true })

<webview>

// Removed
webview.setAttribute('disableguestresize', '')
// There is no replacement for this API

// Removed
webview.setAttribute('guestinstance', instanceId)
// There is no replacement for this API

// Keyboard listeners no longer work on webview tag
webview.onkeydown = () => { /* handler */ }
webview.onkeyup = () => { /* handler */ }

Node Headers URL

這是當建置原生 Node 模組時,在 .npmrc 檔案中指定為 disturl 或作為 --dist-url 命令列標記的 URL。

已棄用:https://atom.io/download/atom-shell

取代為:https://atom.io/download/electron

重大 API 變更 (2.0)

以下清單包含 Electron 2.0 中所做的重大 API 變更。

BrowserWindow

// Deprecated
const optionsA = { titleBarStyle: 'hidden-inset' }
const windowA = new BrowserWindow(optionsA)
// Replace with
const optionsB = { titleBarStyle: 'hiddenInset' }
const windowB = new BrowserWindow(optionsB)
// Removed
menu.popup(browserWindow, 100, 200, 2)
// Replaced with
menu.popup(browserWindow, { x: 100, y: 200, positioningItem: 2 })

nativeImage

// Removed
nativeImage.toPng()
// Replaced with
nativeImage.toPNG()

// Removed
nativeImage.toJpeg()
// Replaced with
nativeImage.toJPEG()

process

  • process.versions.electronprocess.version.chrome 將會設定為唯讀屬性,以便與 Node 設定的其他 process.versions 屬性保持一致。

webContents

// Removed
webContents.setZoomLevelLimits(1, 2)
// Replaced with
webContents.setVisualZoomLevelLimits(1, 2)

webFrame

// Removed
webFrame.setZoomLevelLimits(1, 2)
// Replaced with
webFrame.setVisualZoomLevelLimits(1, 2)

<webview>

// Removed
webview.setZoomLevelLimits(1, 2)
// Replaced with
webview.setVisualZoomLevelLimits(1, 2)

重複的 ARM 資產

每個 Electron 版本都包含兩個相同的 ARM 建置版本,它們的檔案名稱略有不同,例如 electron-v1.7.3-linux-arm.zipelectron-v1.7.3-linux-armv7l.zip。新增了帶有 v7l 前綴的資產,以向使用者說明它支援哪個 ARM 版本,並與未來可能產生的 armv6l 和 arm64 資產進行區分。

沒有前綴的檔案仍然會發佈,以避免破壞可能使用它的任何設定。從 2.0 開始,將不再發佈不帶前綴的檔案。

如需詳細資訊,請參閱 69867189