Skip to main content

重大变化

🌐 Breaking Changes

重大变更将会在此处记录,并在可能的情况下在 JS 代码中添加弃用警告,至少在变更发生前的 一个主要版本 中提示。

🌐 Breaking changes will be documented here, and deprecation warnings added to JS code where possible, at least one major version before the change is made.

重大变更的类型

🌐 Types of Breaking Changes

本文档使用以下约定对重大更改进行分类:

🌐 This document uses the following convention to categorize breaking changes:

  • API 更改: 某个 API 已被修改,未更新代码的调用将保证抛出异常。
  • 行为变化: Electron 的行为已经改变,但这种改变并不会必然导致抛出异常。
  • 默认值已更改: 依赖旧默认值的代码可能会出现问题,但不一定会抛出异常。通过显式指定该值可以恢复旧行为。
  • 已弃用: 某个 API 已被标记为弃用。该 API 将继续正常运行,但会发出弃用警告,并将在未来的版本中被移除。
  • 已移除: 某个 API 或功能已被移除,不再被 Electron 支持。

计划中的破坏性 API 变更(40.0)

🌐 Planned Breaking API Changes (40.0)

已弃用:渲染器进程中的 clipboard API 访问

🌐 Deprecated: clipboard API access from renderer processes

在渲染进程中直接使用 clipboard API 已被弃用。如果你想从渲染进程调用此 API,请将 API 调用放在你的 preload 脚本中,并使用 contextBridge API 暴露它。

🌐 Using the clipboard API directly in the renderer process is deprecated. If you want to call this API from a renderer process, place the API call in your preload script and expose it using the contextBridge API.

行为更改:MacOS dSYM 文件现在使用 tar.xz 压缩

🌐 Behavior Changed: MacOS dSYM files now compressed with tar.xz

MacOS 的调试符号 (dSYM) 现在使用 xz 压缩,以便处理更大的文件。dsym.zip 文件现在是 dsym.tar.xz 文件。使用调试符号的终端用户可能需要更新他们的压缩工具。

🌐 Debug symbols for MacOS (dSYM) now use xz compression in order to handle larger file sizes. dsym.zip files are now dsym.tar.xz files. End users using debug symbols may need to update their zip utilities.

计划中的重大 API 变更 (39.0)

🌐 Planned Breaking API Changes (39.0)

已弃用:--host-rules 命令行开关

🌐 Deprecated: --host-rules command line switch

Chromium 正在弃用 --host-rules 开关。

🌐 Chromium is deprecating the --host-rules switch.

你应该改用 --host-resolver-rules

🌐 You should use --host-resolver-rules instead.

行为已更改:window.open 弹出窗口现在始终可调整大小

🌐 Behavior Changed: window.open popups are always resizable

根据当前的 WHATWG 规范window.open API 现在将始终创建一个可调整大小的弹出窗口。

🌐 Per current WHATWG spec, the window.open API will now always create a resizable popup window.

恢复先前行为:

🌐 To restore previous behavior:

webContents.setWindowOpenHandler((details) => {
return {
action: 'allow',
overrideBrowserWindowOptions: {
resizable: details.features.includes('resizable=yes')
}
}
})

行为已更改:要使用 desktopCapturer,应将 NSAudioCaptureUsageDescription 包含在你的应用的 Info.plist 文件中(🍏 macOS ≥14.2)

🌐 Behavior Changed: NSAudioCaptureUsageDescription should be included in your app's Info.plist file to use desktopCapturer (🍏 macOS ≥14.2)

根据 Chromium 更新,默认启用了苹果的新 CoreAudio Tap API,现在你必须在你的 Info.plist 中定义 NSAudioCaptureUsageDescription 才能使用 desktopCapturer

🌐 Per Chromium update which enables Apple's newer CoreAudio Tap API by default, you now must have NSAudioCaptureUsageDescription defined in your Info.plist to use desktopCapturer.

如果缺少新的权限,Electron 的 desktopCapturer 会创建一个无效的音频流,但不会出现任何错误或警告。这在一定程度上是 Chromium 的副作用,因为如果新系统失败,它不会回退到旧的 Screen & System Audio Recording 权限系统。

🌐 Electron's desktopCapturer will create a dead audio stream if the new permission is absent however no errors or warnings will occur. This is partially a side-effect of Chromium not falling back to the older Screen & System Audio Recording permissions system if the new system fails.

恢复先前行为:

🌐 To restore previous behavior:

// main.js (right beneath your require/import statments)
app.commandLine.appendSwitch(
'disable-features',
'MacCatapLoopbackAudioForScreenShare'
)

行为更改:共享纹理 OSR paint 事件数据结构

🌐 Behavior Changed: shared texture OSR paint event data structure

在使用共享纹理离屏渲染功能时,paint 事件现在会发出一个更结构化的对象。它将 sharedTextureHandleplanesmodifier 移动到统一的 handle 属性中。更多详细信息请参见 OffscreenSharedTexture API 结构。

🌐 When using shared texture offscreen rendering feature, the paint event now emits a more structured object. It moves the sharedTextureHandle, planes, modifier into a unified handle property. See the OffscreenSharedTexture API structure for more details.

计划中的重大 API 变更 (38.0)

🌐 Planned Breaking API Changes (38.0)

已删除:ELECTRON_OZONE_PLATFORM_HINT 环境变量

🌐 Removed: ELECTRON_OZONE_PLATFORM_HINT environment variable

--ozone-platform 标志的默认值已 更改为 auto

🌐 The default value of the --ozone-platform flag changed to auto.

当在 Wayland 会话中启动时(当 XDG_SESSION_TYPE=wayland),Electron 现在默认以原生 Wayland 应用运行。用户可以通过传递 --ozone-platform=x11 强制使用 XWayland。

🌐 Electron now defaults to running as a native Wayland app when launched in a Wayland session (when XDG_SESSION_TYPE=wayland). Users can force XWayland by passing --ozone-platform=x11.

已移除:ORIGINAL_XDG_CURRENT_DESKTOP 环境变量

🌐 Removed: ORIGINAL_XDG_CURRENT_DESKTOP environment variable

以前,Electron 会在内部将 XDG_CURRENT_DESKTOP 的值更改为 Unity,并将桌面会话的原始名称存储在一个单独的变量中。XDG_CURRENT_DESKTOP 不再被覆盖,现在反映的是实际的桌面环境。

🌐 Previously, Electron changed the value of XDG_CURRENT_DESKTOP internally to Unity, and stored the original name of the desktop session in a separate variable. XDG_CURRENT_DESKTOP is no longer overridden and now reflects the actual desktop environment.

已移除:macOS 11 支持

🌐 Removed: macOS 11 support

macOS 11(Big Sur)不再受到 Chromium 的支持。

🌐 macOS 11 (Big Sur) is no longer supported by Chromium.

较旧版本的 Electron 仍可在 Big Sur 上运行,但运行 Electron v38.0.0 及更高版本需要 macOS 12(Monterey)或更高版本。

🌐 Older versions of Electron will continue to run on Big Sur, but macOS 12 (Monterey) or later will be required to run Electron v38.0.0 and higher.

已移除:plugin-crashed 事件

🌐 Removed: plugin-crashed event

plugin-crashed 事件已从 webContents 中移除。

🌐 The plugin-crashed event has been removed from webContents.

已弃用:webFrame.routingId 属性

🌐 Deprecated: webFrame.routingId property

webFrame 对象将不再包含 routingId 属性。

🌐 The routingId property will be removed from webFrame objects.

你应该改用 webFrame.frameToken

🌐 You should use webFrame.frameToken instead.

已弃用:webFrame.findFrameByRoutingId(routingId)

🌐 Deprecated: webFrame.findFrameByRoutingId(routingId)

webFrame.findFrameByRoutingId(routingId) 函数将被移除。

🌐 The webFrame.findFrameByRoutingId(routingId) function will be removed.

你应该改用 webFrame.findFrameByToken(frameToken)

🌐 You should use webFrame.findFrameByToken(frameToken) instead.

计划中的重大 API 变更 (37.0)

🌐 Planned Breaking API Changes (37.0)

实用程序处理未处理的拒绝行为变更

🌐 Utility Process unhandled rejection behavior change

当发生未处理的拒绝时,实用程序进程现在将显示错误消息警告,而不是使进程崩溃。

🌐 Utility Processes will now warn with an error message when an unhandled rejection occurs instead of crashing the process.

要恢复之前的行为,你可以使用:

🌐 To restore the previous behavior, you can use:

process.on('unhandledRejection', () => {
process.exit(1)
})

行为改变:process.exit() 同步杀死实用程序进程

🌐 Behavior Changed: process.exit() kills utility process synchronously

在实用程序进程中调用 process.exit() 现在会同步终止该实用程序进程。这使得 process.exit() 的行为与 Node.js 的行为一致。

🌐 Calling process.exit() in a utility process will now kill the utility process synchronously. This brings the behavior of process.exit() in line with Node.js behavior.

请参考Node.js 文档PR #45690以了解其潜在影响,例如在调用 process.exit() 之前调用 console.log() 时的情况。

🌐 Please refer to the Node.js docs and PR #45690 to understand the potential implications of that, e.g., when calling console.log() before process.exit().

行为变更:WebUSB 和 WebSerial 黑名单支持

🌐 Behavior Changed: WebUSB and WebSerial Blocklist Support

WebUSBWeb Serial 现在支持 Chromium 使用的 WebUSB 黑名单Web Serial 黑名单,并在各自的规范中进行了说明。

要禁用这些功能,用户可以在命令行中传入 disable-usb-blocklistdisable-serial-blocklist 参数。

🌐 To disable these, users can pass disable-usb-blocklist and disable-serial-blocklist as command line flags.

已移除:ProtocolResponsesession 属性的 null

🌐 Removed: null value for session property in ProtocolResponse

此弃用功能已被移除。

🌐 This deprecated feature has been removed.

以前,将 ProtocolResponse.session 属性设置为 null 会创建一个随机独立会话。现在不再支持此功能。

🌐 Previously, setting the ProtocolResponse.session property to null would create a random independent session. This is no longer supported.

由于开销原因,不建议在此使用单用途会话;然而,需要保持这一行为的旧代码可以通过创建一个带有 session.fromPartition(some_random_string) 的随机会话,然后在 ProtocolResponse.session 中使用它来模拟。

🌐 Using single-purpose sessions here is discouraged due to overhead costs; however, old code that needs to preserve this behavior can emulate it by creating a random session with session.fromPartition(some_random_string) and then using it in ProtocolResponse.session.

行为已更改:Linux 上的 BrowserWindow.IsVisibleOnAllWorkspaces()

🌐 Behavior Changed: BrowserWindow.IsVisibleOnAllWorkspaces() on Linux

BrowserWindow.IsVisibleOnAllWorkspaces() 现在在 Linux 上如果窗口当前不可见将返回 false。

计划中重大 API 变更 (36.0)

🌐 Planned Breaking API Changes (36.0)

行为变化:app.commandLine

🌐 Behavior Changes: app.commandLine

app.commandLine 会将大写的开关和参数转换为小写。

app.commandLine 仅用于处理 Chromium 开关(不区分大小写),通过 app.commandLine 传递的开关不会传递给任何子进程。

如果你使用 app.commandLine 来控制主进程的行为,你应该通过 process.argv 来完成此操作。

🌐 If you were using app.commandLine to control the behavior of the main process, you should do this via process.argv.

已弃用:NativeImage.getBitmap()

🌐 Deprecated: NativeImage.getBitmap()

NativeImage.toBitmap() 返回一个新分配的位图副本。NativeImage.getBitmap() 最初是一个可选函数,它返回的是原始位图而不是副本。引入沙盒机制后,这一点发生了改变,所以两者都返回副本,并且在功能上是等效的。

客户端代码应该改为调用 NativeImage.toBitmap()

🌐 Client code should call NativeImage.toBitmap() instead:

// Deprecated
bitmap = image.getBitmap()
// Use this instead
bitmap = image.toBitmap()

已移除:PrinterInfo 上的 isDefaultstatus 属性

🌐 Removed: isDefault and status properties on PrinterInfo

这些属性已从 PrinterInfo 对象中移除,因为它们已从上游 Chromium 中移除。

🌐 These properties have been removed from the PrinterInfo Object because they have been removed from upstream Chromium.

已移除:Session.clearStorageData(options) 中的 quota 类型 syncable

🌐 Removed: quota type syncable in Session.clearStorageData(options)

在调用 Session.clearStorageData(options) 时,类型 options.quotasyncable 已不再受支持,因为它已从上游 Chromium 中移除

🌐 When calling Session.clearStorageData(options), the options.quota type syncable is no longer supported because it has been removed from upstream Chromium.

已弃用:ProtocolResponsesession 属性的 null

🌐 Deprecated: null value for session property in ProtocolResponse

以前,将 ProtocolResponse.session 属性设置为 null 会创建一个随机独立的会话。现在不再支持此功能。

🌐 Previously, setting the ProtocolResponse.session property to null would create a random independent session. This is no longer supported.

由于开销原因,不建议在此使用单用途会话;然而,需要保持这一行为的旧代码可以通过创建一个带有 session.fromPartition(some_random_string) 的随机会话,然后在 ProtocolResponse.session 中使用它来模拟。

🌐 Using single-purpose sessions here is discouraged due to overhead costs; however, old code that needs to preserve this behavior can emulate it by creating a random session with session.fromPartition(some_random_string) and then using it in ProtocolResponse.session.

已弃用:Session.clearStorageData(options) 中的 quota 属性

🌐 Deprecated: quota property in Session.clearStorageData(options)

调用 Session.clearStorageData(options) 时,options.quota 属性已被弃用。由于 syncable 类型已被移除,现在只剩下一个类型 —— 'temporary' —— 因此无需指定它。

🌐 When calling Session.clearStorageData(options), the options.quota property is deprecated. Since the syncable type was removed, there is only one type left -- 'temporary' -- so specifying it is unnecessary.

已弃用:session 的扩展方法和事件

🌐 Deprecated: Extension methods and events on session

session.loadExtensionsession.removeExtensionsession.getExtensionsession.getAllExtensions、“extension-loaded”事件、“extension-unloaded”事件以及“extension-ready”事件都已迁移到新的session.extensions类。

已移除:systemPreferences.isAeroGlassEnabled()

🌐 Removed: systemPreferences.isAeroGlassEnabled()

systemPreferences.isAeroGlassEnabled() 函数已被删除且没有替代方法。自 Electron 23 起,它一直返回 true,而 Electron 23 仅支持 Windows 10 及更高版本,在这些系统中无法再禁用 DWM 组合效果。

🌐 The systemPreferences.isAeroGlassEnabled() function has been removed without replacement. It has been always returning true since Electron 23, which only supports Windows 10+, where DWM composition can no longer be disabled.

https://learn.microsoft.com/en-us/windows/win32/dwm/composition-ovw#disabling-dwm-composition-windows7-and-earlier

已更改:运行 GNOME 时默认使用 GTK 4

🌐 Changed: GTK 4 is default when running GNOME

在进行上游更改之后,运行 GNOME 时默认使用 GTK 4。

🌐 After an upstream change, GTK 4 is now the default when running GNOME.

在极少数情况下,这可能导致某些应用或配置出现如下消息的错误

🌐 In rare cases, this may cause some applications or configurations to error with the following message:

Gtk-ERROR **: 11:30:38.382: GTK 2/3 symbols detected. Using GTK 2/3 and GTK 4 in the same process is not supported

受影响的用户可以通过指定 gtk-version 命令行标志来解决此问题:

🌐 Affected users can work around this by specifying the gtk-version command-line flag:

$ electron --gtk-version=3   # or --gtk-version=2

同样可以使用 app.commandLine.appendSwitch 函数来完成。

🌐 The same can be done with the app.commandLine.appendSwitch function.

计划中的重大 API 更改(35.0)

🌐 Planned Breaking API Changes (35.0)

行为变化:Linux 上 Dialog API 的 defaultPath 选项

🌐 Behavior Changed: Dialog API's defaultPath option on Linux

在 Linux 上,文件对话框所需的 portal 版本已从 4 回退到 3。当使用 portal 文件选择对话框时,除非 portal 后端版本为 4 或更高,否则不支持使用 Dialog API 的 defaultPath 选项。可以使用 --xdg-portal-required-version 命令行开关 来为你的应用强制指定所需版本。更多详情请参见 #44426

🌐 On Linux, the required portal version for file dialogs has been reverted to 3 from 4. Using the defaultPath option of the Dialog API is not supported when using portal file chooser dialogs unless the portal backend is version 4 or higher. The --xdg-portal-required-version command-line switch can be used to force a required version for your application. See #44426 for more details.

已弃用:getFromVersionIDsession.serviceWorkers

🌐 Deprecated: getFromVersionID on session.serviceWorkers

session.serviceWorkers.fromVersionID(versionId) API 已被废弃,取而代之的是 session.serviceWorkers.getInfoFromVersionID(versionId)。此更改旨在通过引入 session.serviceWorkers.getWorkerFromVersionID(versionId) API,更清楚地显示返回的是哪个对象。

🌐 The session.serviceWorkers.fromVersionID(versionId) API has been deprecated in favor of session.serviceWorkers.getInfoFromVersionID(versionId). This was changed to make it more clear which object is returned with the introduction of the session.serviceWorkers.getWorkerFromVersionID(versionId) API.

// Deprecated
session.serviceWorkers.fromVersionID(versionId)

// Replace with
session.serviceWorkers.getInfoFromVersionID(versionId)

已弃用:setPreloadsgetPreloadsSession

🌐 Deprecated: setPreloads, getPreloads on Session

registerPreloadScriptunregisterPreloadScriptgetPreloadScripts 被引入用于替代已弃用的方法。这些新 API 允许第三方库注册预加载脚本,而不替换现有脚本。此外,新的 type 选项允许在 frame 之外添加额外的预加载目标。

// Deprecated
session.setPreloads([path.join(__dirname, 'preload.js')])

// Replace with:
session.registerPreloadScript({
type: 'frame',
id: 'app-preload',
filePath: path.join(__dirname, 'preload.js')
})

已弃用:在 WebContentsconsole-message 事件中使用 levelmessagelinesourceId 参数

🌐 Deprecated: level, message, line, and sourceId arguments in console-message event on WebContents

WebContents 上的 console-message 事件已更新,以提供有关 Event 参数的详细信息。

🌐 The console-message event on WebContents has been updated to provide details on the Event argument.

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

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

此外,level 现在是一个字符串,可能的取值为 infowarningerrordebug

🌐 Additionally, level is now a string with possible values of info, warning, error, and debug.

行为已更改:WebRequestFilterurls 属性。

🌐 Behavior Changed: urls property of WebRequestFilter.

以前,空的 urls 数组被解释为包含所有 URL。现在,开发者如果想明确包含所有 URL,应该使用 <all_urls> 模式,这是一个指定的 URL 模式,可以匹配所有可能的 URL。此更改明确了意图,并确保行为更加可预测。

🌐 Previously, an empty urls array was interpreted as including all URLs. To explicitly include all URLs, developers should now use the <all_urls> pattern, which is a designated URL pattern that matches every possible URL. This change clarifies the intent and ensures more predictable behavior.

// Deprecated
const deprecatedFilter = {
urls: []
}

// Replace with
const newFilter = {
urls: ['<all_urls>']
}

已弃用:systemPreferences.isAeroGlassEnabled()

🌐 Deprecated: systemPreferences.isAeroGlassEnabled()

systemPreferences.isAeroGlassEnabled() 函数已被弃用且没有替代方案。自 Electron 23 起,它一直返回 true,因为该版本仅支持 Windows 10 及更高版本,而 DWM 组合已无法再被禁用。

🌐 The systemPreferences.isAeroGlassEnabled() function has been deprecated without replacement. It has been always returning true since Electron 23, which only supports Windows 10+, where DWM composition can no longer be disabled.

https://learn.microsoft.com/en-us/windows/win32/dwm/composition-ovw#disabling-dwm-composition-windows7-and-earlier

计划中的重大 API 更改(34.0)

🌐 Planned Breaking API Changes (34.0)

行为已更改:在 Windows 全屏时,菜单栏将被隐藏

🌐 Behavior Changed: menu bar will be hidden during fullscreen on Windows

这使行为与 Linux 保持一致。之前的行为:在 Windows 全屏时菜单栏仍然可见。新的行为:在 Windows 全屏时菜单栏被隐藏。

🌐 This brings the behavior to parity with Linux. Prior behavior: Menu bar is still visible during fullscreen on Windows. New behavior: Menu bar is hidden during fullscreen on Windows.

更正:这之前被列为 Electron 33 的重大更改,但实际上首次发布是在 Electron 34。

计划中的重大 API 更改 (33.0)

🌐 Planned Breaking API Changes (33.0)

已弃用:document.execCommand("paste")

🌐 Deprecated: document.execCommand("paste")

同步剪贴板读取 API document.execCommand("paste") 已被弃用,取而代之的是 异步剪贴板 API。这是为了与浏览器的默认行为保持一致。

🌐 The synchronous clipboard read API document.execCommand("paste") has been deprecated in favor of async clipboard API. This is to align with the browser defaults.

WebPreferences 上的 enableDeprecatedPaste 选项会触发此 API 的权限检查以及相关的权限类型 deprecated-sync-clipboard-read,这一选项也已被弃用。

🌐 The enableDeprecatedPaste option on WebPreferences that triggers the permission checks for this API and the associated permission type deprecated-sync-clipboard-read are also deprecated.

行为已更改:框架属性可能会检索到已分离的 WebFrameMain 实例,或者根本无法检索

🌐 Behavior Changed: frame properties may retrieve detached WebFrameMain instances or none at all

提供访问 WebFrameMain 实例的 API 可能会返回一个 frame.detached 被设置为 true 的实例,或者可能返回 null

🌐 APIs which provide access to a WebFrameMain instance may return an instance with frame.detached set to true, or possibly return null.

当一个框架执行跨源导航时,它会进入一种分离状态,此时它不再附加到页面。在这种状态下,它可能会在被删除之前运行卸载处理程序。如果在此状态期间发送 IPC,frame.detached 将被设置为 true,随后框架将被销毁。

🌐 When a frame performs a cross-origin navigation, it enters into a detached state in which it's no longer attached to the page. In this state, it may be running unload handlers prior to being deleted. In the event of an IPC sent during this state, frame.detached will be set to true with the frame being destroyed shortly thereafter.

在接收到事件时,重要的是在接收时立即访问 WebFrameMain 的属性。否则,不保证它指向的网页与接收时相同。为了避免预期不一致,当网页已更改且访问延迟时,Electron 将返回 null

🌐 When receiving an event, it's important to access WebFrameMain properties immediately upon being received. Otherwise, it's not guaranteed to point to the same webpage as when received. To avoid misaligned expectations, Electron will return null in the case of late access where the webpage has changed.

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 处理

🌐 Behavior Changed: custom protocol URL handling on Windows

由于 Chromium 为支持 非特殊方案 URL 所做的更改,使用 Windows 文件路径的自定义协议 URL 在已弃用的 protocol.registerFileProtocol 以及 BrowserWindow.loadURLWebContents.loadURL<webview>.loadURL 上的 baseURLForDataURL 属性中将不再能正常工作。protocol.handle 也无法与这些类型的 URL 一起使用,但这并不是一个变化,因为它一直都是这样的。

🌐 Due to changes made in Chromium to support Non-Special Scheme URLs, custom protocol URLs that use Windows file paths will no longer work correctly with the deprecated protocol.registerFileProtocol and the baseURLForDataURL property on BrowserWindow.loadURL, WebContents.loadURL, and <webview>.loadURL. protocol.handle will also not work with these types of URLs but this is not a change since it has always worked that way.

// 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')

行为已更改:app 上的 loginwebContents 属性

🌐 Behavior Changed: webContents property on login on app

applogin 事件中的 webContents 属性在使用 respondToAuthRequestsFromMainProcess 选项创建的实用程序进程的请求触发事件时将为 null

🌐 The webContents property in the login event from app will be null when the event is triggered for requests from the utility process created with respondToAuthRequestsFromMainProcess option.

已弃用:BrowserWindowConstructorOption.type 中的 textured 选项

🌐 Deprecated: textured option in BrowserWindowConstructorOption.type

BrowserWindowConstructorOptionstypetextured 选项已被弃用,且没有替代方案。该选项依赖于 macOS 上的 NSWindowStyleMaskTexturedBackground 样式掩码,而该掩码也已被弃用且没有替代方案。

🌐 The textured option of type in BrowserWindowConstructorOptions has been deprecated with no replacement. This option relied on the NSWindowStyleMaskTexturedBackground style mask on macOS, which has been deprecated with no alternative.

已移除:macOS 10.15 支持

🌐 Removed: macOS 10.15 support

macOS 10.15(Catalina)不再受到 Chromium 的支持。

🌐 macOS 10.15 (Catalina) is no longer supported by Chromium.

较旧版本的 Electron 将继续在 Catalina 上运行,但要运行 Electron v33.0.0 及更高版本,则需要 macOS 11(Big Sur)或更高版本。

🌐 Older versions of Electron will continue to run on Catalina, but macOS 11 (Big Sur) or later will be required to run Electron v33.0.0 and higher.

行为改变:本地模块现在需要 C++20

🌐 Behavior Changed: Native modules now require C++20

由于上游的变更,V8Node.js 现在都至少需要 C++20。使用原生 Node 模块的开发者应使用 --std=c++20 而不是 --std=c++17 来构建他们的模块。使用 gcc9 或更低版本的镜像可能需要升级到 gcc10 以便编译。更多细节请参见 #43555

🌐 Due to changes made upstream, both V8 and Node.js now require C++20 as a minimum version. Developers using native node modules should build their modules with --std=c++20 rather than --std=c++17. Images using gcc9 or lower may need to update to gcc10 in order to compile. See #43555 for more details.

已弃用:systemPreferences.accessibilityDisplayShouldReduceTransparency

🌐 Deprecated: systemPreferences.accessibilityDisplayShouldReduceTransparency

systemPreferences.accessibilityDisplayShouldReduceTransparency 属性现在已被弃用,建议使用新的 nativeTheme.prefersReducedTransparency,它提供相同的信息并且支持跨平台。

🌐 The systemPreferences.accessibilityDisplayShouldReduceTransparency property is now deprecated in favor of the new nativeTheme.prefersReducedTransparency, which provides identical information and works cross-platform.

// Deprecated
const shouldReduceTransparency = systemPreferences.accessibilityDisplayShouldReduceTransparency

// Replace with:
const prefersReducedTransparency = nativeTheme.prefersReducedTransparency

计划中的重大 API 更改 (32.0)

🌐 Planned Breaking API Changes (32.0)

已移除:File.path

🌐 Removed: File.path

Web File 对象的非标准 path 属性是在早期版本的 Electron 中添加的,作为处理本地文件的一种便捷方法,当时在渲染器中进行所有操作更为常见。然而,它偏离了标准,同时也存在一定的安全风险,因此从 Electron 32.0 开始,该属性已被移除,改为使用 webUtils.getPathForFile 方法。

🌐 The nonstandard path property of the Web File object was added in an early version of Electron as a convenience method for working with native files when doing everything in the renderer was more common. However, it represents a deviation from the standard and poses a minor security risk as well, so beginning in Electron 32.0 it has been removed in favor of the webUtils.getPathForFile method.

// 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}`)
}
})

已弃用:clearHistorycanGoBackgoBackcanGoForwardgoForwardgoToIndexcanGoToOffsetgoToOffsetWebContents

🌐 Deprecated: clearHistory, canGoBack, goBack, canGoForward, goForward, goToIndex, canGoToOffset, goToOffset on WebContents

与导航相关的 API 现已弃用。

🌐 The navigation-related APIs are now deprecated.

这些 API 已被移到 WebContentsnavigationHistory 属性,以提供一个更结构化、更直观的接口来管理导航历史。

🌐 These APIs have been moved to the navigationHistory property of WebContents to provide a more structured and intuitive interface for managing navigation history.

// 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)

行为已更改:userData 中的目录 databases 将被删除

🌐 Behavior changed: Directory databases in userData will be deleted

如果你在 app.getPath('userData') 返回的目录中有一个名为 databases 的目录,它将在首次运行 Electron 32 时被删除。 databases 目录曾被 WebSQL 使用,而 WebSQL 在 Electron 31 中已被移除。Chromium 现在会执行清理操作,删除此目录。详见 issue #45396

🌐 If you have a directory called databases in the directory returned by app.getPath('userData'), it will be deleted when Electron 32 is first run. The databases directory was used by WebSQL, which was removed in Electron 31. Chromium now performs a cleanup that deletes this directory. See issue #45396.

计划中的重大 API 更改 (31.0)

🌐 Planned Breaking API Changes (31.0)

已移除:WebSQL 支持

🌐 Removed: WebSQL support

Chromium 已经在上游移除了对 WebSQL 的支持,将其转为仅在 Android 上使用。有关更多信息,请参阅 Chromium 关于移除的讨论意图

🌐 Chromium has removed support for WebSQL upstream, transitioning it to Android only. See Chromium's intent to remove discussion for more information.

行为已更改:nativeImage.toDataURL 将保留 PNG 颜色空间

🌐 Behavior Changed: nativeImage.toDataURL will preserve PNG colorspace

PNG 解码器的实现已更改以保留颜色空间数据,该函数返回的编码数据现在与之匹配。

🌐 PNG decoder implementation has been changed to preserve colorspace data, the encoded data returned from this function now matches it.

有关更多信息,请参见 crbug.com/332584706

🌐 See crbug.com/332584706 for more information.

行为变化:window.flashFrame(bool) 在 macOS 上会持续闪烁 Dock 图标

🌐 Behavior Changed: window.flashFrame(bool) will flash dock icon continuously on macOS

这使得行为与 Windows 和 Linux 保持一致。之前的行为:第一个 flashFrame(true) 只会让 Dock 图标弹跳一次(使用 NSInformationalRequest 级别),而 flashFrame(false) 则没有任何作用。新的行为:持续闪烁直到调用 flashFrame(false) 为止。这改为使用 NSCriticalRequest 级别。要明确使用 NSInformationalRequest 以使 Dock 图标单次弹跳,仍然可以使用 dock.bounce('informational')

🌐 This brings the behavior to parity with Windows and Linux. Prior behavior: The first flashFrame(true) bounces the dock icon only once (using the NSInformationalRequest level) and flashFrame(false) does nothing. New behavior: Flash continuously until flashFrame(false) is called. This uses the NSCriticalRequest level instead. To explicitly use NSInformationalRequest to cause a single dock icon bounce, it is still possible to use dock.bounce('informational').

计划中的重大 API 更改 (30.0)

🌐 Planned Breaking API Changes (30.0)

行为更改:跨源 iframe 现在使用权限策略访问功能

🌐 Behavior Changed: cross-origin iframes now use Permission Policy to access features

跨来源的 iframe 现在必须通过 allow 属性指定特定 iframe 可用的功能,才能访问这些功能。

🌐 Cross-origin iframes must now specify features available to a given iframe via the allow attribute in order to access them.

有关更多信息,请参见文档

🌐 See documentation for more information.

已移除:--disable-color-correct-rendering 开关

🌐 Removed: The --disable-color-correct-rendering switch

这个开关从未被正式记录,但无论如何,这里仍记录了它的删除情况。Chromium 本身现在对色彩空间有更好的支持,因此不再需要这个标志。

🌐 This switch was never formally documented but its removal is being noted here regardless. Chromium itself now has better support for color spaces so this flag should not be needed.

行为已改变:macOS 上的 BrowserView.setAutoResize 行为

🌐 Behavior Changed: BrowserView.setAutoResize behavior on macOS

在 Electron 30 中,BrowserView 现在是新的 WebContentsView API 的一个封装。

🌐 In Electron 30, BrowserView is now a wrapper around the new WebContentsView API.

之前,BrowserView API 的 setAutoResize 函数在 macOS 上依赖于 自动调整大小,而在 Windows 和 Linux 上则使用自定义算法。 对于一些简单的用例,例如让 BrowserView 填满整个窗口,这两种方法的行为是相同的。 然而,在更复杂的情况下,BrowserView 在 macOS 上的自动调整大小行为会与其他平台不同,因为 Windows 和 Linux 的自定义调整算法并不能完美匹配 macOS 自动调整大小 API 的行为。 现在,自动调整大小的行为已在所有平台上统一。

🌐 Previously, the setAutoResize function of the BrowserView API was backed by autoresizing on macOS, and by a custom algorithm on Windows and Linux. For simple use cases such as making a BrowserView fill the entire window, the behavior of these two approaches was identical. However, in more advanced cases, BrowserViews would be autoresized differently on macOS than they would be on other platforms, as the custom resizing algorithm for Windows and Linux did not perfectly match the behavior of macOS's autoresizing API. The autoresizing behavior is now standardized across all platforms.

如果你的应用使用 BrowserView.setAutoResize 来执行比让 BrowserView 填充整个窗口更复杂的操作,那么你很可能已经有自定义逻辑来处理 macOS 上这种行为的差异。 如果是这样,那么在 Electron 30 中就不再需要这些逻辑,因为自动调整大小的行为是一致的。

🌐 If your app uses BrowserView.setAutoResize to do anything more complex than making a BrowserView fill the entire window, it's likely you already had custom logic in place to handle this difference in behavior on macOS. If so, that logic will no longer be needed in Electron 30 as autoresizing behavior is consistent.

已弃用:BrowserView

🌐 Deprecated: BrowserView

BrowserView 类已被弃用,取而代之的是新的 WebContentsView 类。

🌐 The BrowserView class has been deprecated and replaced by the new WebContentsView class.

BrowserWindow 中与 BrowserView 相关的方法也已被弃用:

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

已移除:WebContentscontext-menuparams.inputFormType 属性

🌐 Removed: params.inputFormType property on context-menu on WebContents

WebContentscontext-menu 事件中 params 对象的 inputFormType 属性已被移除。请改用新的 formControlType 属性。

🌐 The inputFormType property of the params object in the context-menu event from WebContents has been removed. Use the new formControlType property instead.

已移除:process.getIOCounters()

🌐 Removed: process.getIOCounters()

Chromium 已删除对此信息的访问。

🌐 Chromium has removed access to this information.

计划中的重大 API 更改 (29.0)

🌐 Planned Breaking API Changes (29.0)

行为已更改:ipcRenderer 不能再通过 contextBridge 发送

🌐 Behavior Changed: ipcRenderer can no longer be sent over the contextBridge

尝试将整个 ipcRenderer 模块作为对象通过 contextBridge 发送,现在会导致桥接接收端收到一个空对象。此更改是为了消除/减轻安全风险。你不应直接在桥接中暴露 ipcRenderer 或其方法。相反,应提供如下的安全封装器:

🌐 Attempting to send the entire ipcRenderer module as an object over the contextBridge will now result in an empty object on the receiving side of the bridge. This change was made to remove / mitigate a security footgun. You should not directly expose ipcRenderer or its methods over the bridge. Instead, provide a safe wrapper like below:

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

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

🌐 Removed: renderer-process-crashed event on app

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

🌐 The renderer-process-crashed event on app has been removed. Use the new render-process-gone event instead.

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

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

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

🌐 Removed: crashed event on WebContents and <webview>

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

🌐 The crashed events on WebContents and <webview> have been removed. Use the new render-process-gone event instead.

// 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 事件

🌐 Removed: gpu-process-crashed event on app

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

🌐 The gpu-process-crashed event on app has been removed. Use the new child-process-gone event instead.

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

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

计划中的重大 API 更改 (28.0)

🌐 Planned Breaking API Changes (28.0)

行为已更改:将 WebContents.backgroundThrottling 设置为 false 会影响主机 BrowserWindow 中的所有 WebContents

🌐 Behavior Changed: WebContents.backgroundThrottling set to false affects all WebContents in the host BrowserWindow

WebContents.backgroundThrottling 设置为 false 将禁用 BrowserWindow 中所有由其显示的 WebContents 的帧率限制。

已移除:BrowserWindow.setTrafficLightPosition(position)

🌐 Removed: BrowserWindow.setTrafficLightPosition(position)

BrowserWindow.setTrafficLightPosition(position) 已被移除,应改用 BrowserWindow.setWindowButtonPosition(position) API,该 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()

🌐 Removed: 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()

🌐 Removed: ipcRenderer.sendTo()

ipcRenderer.sendTo() API 已被移除。应该通过在渲染器之间设置 MessageChannel 来替代。

🌐 The ipcRenderer.sendTo() API has been removed. It should be replaced by setting up a MessageChannel between the renderers.

IpcRendererEventsenderIdsenderIsMainFrame 属性也已被移除。

🌐 The senderId and senderIsMainFrame properties of IpcRendererEvent have been removed as well.

已移除:app.runningUnderRosettaTranslation

🌐 Removed: app.runningUnderRosettaTranslation

app.runningUnderRosettaTranslation 属性已被移除。请使用 app.runningUnderARM64Translation

🌐 The app.runningUnderRosettaTranslation property has been removed. Use app.runningUnderARM64Translation instead.

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

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

🌐 Deprecated: renderer-process-crashed event on app

app 上的 renderer-process-crashed 事件已被弃用。请改用新的 render-process-gone 事件。

🌐 The renderer-process-crashed event on app has been deprecated. Use the new render-process-gone event instead.

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

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

已弃用:WebContents 上的 context-menuparams.inputFormType 属性

🌐 Deprecated: params.inputFormType property on context-menu on WebContents

WebContentscontext-menu 事件中 params 对象的 inputFormType 属性已被弃用。请改用新的 formControlType 属性。

🌐 The inputFormType property of the params object in the context-menu event from WebContents has been deprecated. Use the new formControlType property instead.

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

🌐 Deprecated: crashed event on WebContents and <webview>

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

🌐 The crashed events on WebContents and <webview> have been deprecated. Use the new render-process-gone event instead.

// 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 事件

🌐 Deprecated: gpu-process-crashed event on app

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

🌐 The gpu-process-crashed event on app has been deprecated. Use the new child-process-gone event instead.

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

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

计划中的重大 API 更改 (27.0)

🌐 Planned Breaking API Changes (27.0)

已移除:支持 macOS 10.13 / 10.14

🌐 Removed: macOS 10.13 / 10.14 support

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

🌐 macOS 10.13 (High Sierra) and macOS 10.14 (Mojave) are no longer supported by Chromium.

旧版本的 Electron 仍然可以在这些操作系统上运行,但运行 Electron v27.0.0 及更高版本将需要 macOS 10.15(Catalina)或更高版本。

🌐 Older versions of Electron will continue to run on these operating systems, but macOS 10.15 (Catalina) or later will be required to run Electron v27.0.0 and higher.

已弃用:ipcRenderer.sendTo()

🌐 Deprecated: ipcRenderer.sendTo()

ipcRenderer.sendTo() API 已被弃用。应该通过在渲染器之间设置 MessageChannel 来替代。

🌐 The ipcRenderer.sendTo() API has been deprecated. It should be replaced by setting up a MessageChannel between the renderers.

IpcRendererEventsenderIdsenderIsMainFrame 属性也已被弃用。

🌐 The senderId and senderIsMainFrame properties of IpcRendererEvent have been deprecated as well.

已移除:systemPreferences 中的配色方案事件

🌐 Removed: color scheme events in systemPreferences

以下 systemPreferences 事件已被移除:

🌐 The following systemPreferences events have been removed:

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

请改用 nativeTheme 模块上的新 updated 事件。

🌐 Use the new updated event on the nativeTheme module instead.

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

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

已移除:macOS 上的一些 window.setVibrancy 选项

🌐 Removed: Some window.setVibrancy options on macOS

以下活力选项已被删除:

🌐 The following vibrancy options have been removed:

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

它们之前已被弃用,并已被 Apple 在 10.15 中删除。

🌐 These were previously deprecated and have been removed by Apple in 10.15.

已移除:webContents.getPrinters

🌐 Removed: webContents.getPrinters

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

🌐 The webContents.getPrinters method has been removed. Use webContents.getPrintersAsync instead.

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

🌐 Removed: systemPreferences.{get,set}AppLevelAppearance and systemPreferences.appLevelAppearance

systemPreferences.getAppLevelAppearancesystemPreferences.setAppLevelAppearance 方法已被移除,systemPreferences.appLevelAppearance 属性也已被移除。请改用 nativeTheme 模块。

🌐 The systemPreferences.getAppLevelAppearance and systemPreferences.setAppLevelAppearance methods have been removed, as well as the systemPreferences.appLevelAppearance property. Use the nativeTheme module instead.

// 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

🌐 Removed: alternate-selected-control-text value for systemPreferences.getColor

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

🌐 The alternate-selected-control-text value for systemPreferences.getColor has been removed. Use selected-content-background instead.

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

计划中的重大 API 更改 (26.0)

🌐 Planned Breaking API Changes (26.0)

已弃用:webContents.getPrinters

🌐 Deprecated: webContents.getPrinters

webContents.getPrinters 方法已被弃用。请改用 webContents.getPrintersAsync

🌐 The webContents.getPrinters method has been deprecated. Use webContents.getPrintersAsync instead.

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

🌐 Deprecated: systemPreferences.{get,set}AppLevelAppearance and systemPreferences.appLevelAppearance

systemPreferences.getAppLevelAppearancesystemPreferences.setAppLevelAppearance 方法已被弃用,systemPreferences.appLevelAppearance 属性也不再使用。请改用 nativeTheme 模块。

🌐 The systemPreferences.getAppLevelAppearance and systemPreferences.setAppLevelAppearance methods have been deprecated, as well as the systemPreferences.appLevelAppearance property. Use the nativeTheme module instead.

// 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

🌐 Deprecated: alternate-selected-control-text value for systemPreferences.getColor

systemPreferences.getColoralternate-selected-control-text 值已被弃用。请改用 selected-content-background

🌐 The alternate-selected-control-text value for systemPreferences.getColor has been deprecated. Use selected-content-background instead.

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

计划中的重大 API 更改 (25.0)

🌐 Planned Breaking API Changes (25.0)

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

🌐 Deprecated: protocol.{un,}{register,intercept}{Buffer,String,Stream,File,Http}Protocol and protocol.isProtocol{Registered,Intercepted}

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

🌐 The protocol.register*Protocol and protocol.intercept*Protocol methods have been replaced with protocol.handle.

这种新方法可以注册新的协议或拦截现有协议,并且响应可以是任何类型。

🌐 The new method can either register a new protocol or intercept an existing protocol, and responses can be of any type.

// 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.nodejs.cn' })
})

// Replace with
protocol.handle('some-protocol', () => {
return net.fetch('https://electron.nodejs.cn')
})
// 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)

🌐 Deprecated: BrowserWindow.setTrafficLightPosition(position)

BrowserWindow.setTrafficLightPosition(position) 已被弃用,应改用 BrowserWindow.setWindowButtonPosition(position) API,该 API 接受 null 而不是 { x: 0, y: 0 } 来将位置重置为系统默认值。

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

🌐 Deprecated: BrowserWindow.getTrafficLightPosition()

BrowserWindow.getTrafficLightPosition() 已被弃用,应使用 BrowserWindow.getWindowButtonPosition() 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)

🌐 Planned Breaking API Changes (24.0)

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

🌐 API Changed: nativeImage.createThumbnailFromPath(path, size)

maxSize 参数已更改为 size,以反映传入的大小将是生成的缩略图的大小。之前,如果图片小于 maxSize,Windows 不会放大图片,而 macOS 总是将大小设置为 maxSize。现在各平台的行为一致。

🌐 The maxSize parameter has been changed to size to reflect that the size passed in will be the size the thumbnail created. Previously, Windows would not scale the image up if it were smaller than maxSize, and macOS would always set the size to maxSize. Behavior is now the same across platforms.

更新的行为:

🌐 Updated Behavior:

// 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 上):

🌐 Previous Behavior (on 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)

🌐 Planned Breaking API Changes (23.0)

行为已更改:macOS 上的可拖动区域

🌐 Behavior Changed: Draggable Regions on macOS

在 macOS 上,可拖动区域(使用 CSS 属性 -webkit-app-region: drag )的实现已经更改,以与 Windows 和 Linux 保持一致。以前,当一个带有 -webkit-app-region: no-drag 的区域与一个带有 -webkit-app-region: drag 的区域重叠时,macOS 上的 no-drag 区域总是优先显示,而不考虑 CSS 层叠顺序。也就是说,如果一个 drag 区域在一个 no-drag 区域上方,它会被忽略。从 Electron 23 开始,位于 no-drag 区域上方的 drag 区域将会正确地使该区域可拖动。

🌐 The implementation of draggable regions (using the CSS property -webkit-app-region: drag) has changed on macOS to bring it in line with Windows and Linux. Previously, when a region with -webkit-app-region: no-drag overlapped a region with -webkit-app-region: drag, the no-drag region would always take precedence on macOS, regardless of CSS layering. That is, if a drag region was above a no-drag region, it would be ignored. Beginning in Electron 23, a drag region on top of a no-drag region will correctly cause the region to be draggable.

此外,之前 customButtonsOnHover BrowserWindow 属性创建了一个可拖动区域,该区域会忽略 -webkit-app-region CSS 属性。现在这一问题已经修复(讨论见 #37210)。

🌐 Additionally, the customButtonsOnHover BrowserWindow property previously created a draggable region which ignored the -webkit-app-region CSS property. This has now been fixed (see #37210 for discussion).

因此,如果你的应用在 macOS 上使用具有可拖动区域的无框架窗口,则应用中的可拖动区域可能会在 Electron 23 中发生变化。

🌐 As a result, if your app uses a frameless window with draggable regions on macOS, the regions which are draggable in your app may change in Electron 23.

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

🌐 Removed: Windows 7 / 8 / 8.1 support

不再支持 Windows 7、Windows 8 和 Windows 8.1。Electron 遵循既定的 Chromium 弃用政策,该政策将 从 Chromium 109 开始弃用对 Windows 7 的支持

旧版本的 Electron 将继续在这些操作系统上运行,但需要 Windows 10 或更高版本才能运行 Electron v23.0.0 及更高版本。

🌐 Older versions of Electron will continue to run on these operating systems, but Windows 10 or later will be required to run Electron v23.0.0 and higher.

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

🌐 Removed: BrowserWindow scroll-touch-* events

BrowserWindow 上已删除不推荐使用的 scroll-touch-beginscroll-touch-endscroll-touch-edge 事件。取而代之的是,使用 WebContents 上新提供的 input-event 事件

🌐 The deprecated scroll-touch-begin, scroll-touch-end and scroll-touch-edge events on BrowserWindow have been removed. Instead, use the newly available input-event event on WebContents.

// 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)

🌐 Removed: webContents.incrementCapturerCount(stayHidden, stayAwake)

webContents.incrementCapturerCount(stayHidden, stayAwake) 函数已被移除。 当页面捕获完成时,现在由 webContents.capturePage 自动处理。

🌐 The webContents.incrementCapturerCount(stayHidden, stayAwake) function has been removed. It is now automatically handled by webContents.capturePage when a page capture completes.

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)

🌐 Removed: webContents.decrementCapturerCount(stayHidden, stayAwake)

webContents.decrementCapturerCount(stayHidden, stayAwake) 函数已被移除。 当页面捕获完成时,现在由 webContents.capturePage 自动处理。

🌐 The webContents.decrementCapturerCount(stayHidden, stayAwake) function has been removed. It is now automatically handled by webContents.capturePage when a page capture completes.

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)

🌐 Planned Breaking API Changes (22.0)

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

🌐 Deprecated: 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)

🌐 Deprecated: 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 事件

🌐 Removed: WebContents new-window event

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

🌐 The new-window event of WebContents has been removed. It is replaced by webContents.setWindowOpenHandler().

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

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

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

🌐 Removed: <webview> new-window event

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

🌐 The new-window event of <webview> has been removed. There is no direct replacement.

// 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-* 事件

🌐 Deprecated: BrowserWindow scroll-touch-* events

BrowserWindow 上的 scroll-touch-beginscroll-touch-endscroll-touch-edge 事件已不推荐使用。请改为使用 WebContents 上新提供的 input-event 事件

🌐 The scroll-touch-begin, scroll-touch-end and scroll-touch-edge events on BrowserWindow are deprecated. Instead, use the newly available input-event event on WebContents.

// 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)

🌐 Planned Breaking API Changes (21.0)

行为已更改:已启用 V8 内存笼

🌐 Behavior Changed: V8 Memory Cage enabled

V8 内存笼已启用,这对使用 ArrayBufferBuffer 封装非 V8 内存的本地模块有影响。有关更多详细信息,请参阅关于 V8 内存笼的博客文章

🌐 The V8 memory cage has been enabled, which has implications for native modules which wrap non-V8 memory with ArrayBuffer or Buffer. See the blog post about the V8 memory cage for more details.

API 已更改:webContents.printToPDF()

🌐 API Changed: webContents.printToPDF()

webContents.printToPDF() 已被修改以符合 Chrome DevTools 协议中的 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)

🌐 Planned Breaking API Changes (20.0)

已移除:支持 macOS 10.11 / 10.12

🌐 Removed: macOS 10.11 / 10.12 support

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

🌐 macOS 10.11 (El Capitan) and macOS 10.12 (Sierra) are no longer supported by Chromium.

旧版本的 Electron 仍然可以在这些操作系统上运行,但运行 Electron v20.0.0 及更高版本需要 macOS 10.13(High Sierra)或更高版本。

🌐 Older versions of Electron will continue to run on these operating systems, but macOS 10.13 (High Sierra) or later will be required to run Electron v20.0.0 and higher.

默认更改:没有 nodeIntegration: true 的渲染器默认处于沙盒模式

🌐 Default Changed: renderers without nodeIntegration: true are sandboxed by default

以前,指定预加载脚本的渲染器默认是不受沙箱限制的。这意味着默认情况下,预加载脚本可以访问 Node.js。在 Electron 20 中,这一默认设置发生了变化。从 Electron 20 开始,渲染器将默认处于沙箱模式,除非指定了 nodeIntegration: truesandbox: false

🌐 Previously, renderers that specified a preload script defaulted to being unsandboxed. This meant that by default, preload scripts had access to Node.js. In Electron 20, this default has changed. Beginning in Electron 20, renderers will be sandboxed by default, unless nodeIntegration: true or sandbox: false is specified.

如果你的预加载脚本不依赖于 Node,则无需采取任何措施。如果你的预加载脚本确实依赖于 Node,则需要重构它们以移除渲染器中的 Node 使用,或为相关的渲染器明确指定 sandbox: false

🌐 If your preload scripts do not depend on Node, no action is needed. If your preload scripts do depend on Node, either refactor them to remove Node usage from the renderer, or explicitly specify sandbox: false for the relevant renderers.

已删除:Linux 上的 skipTaskbar

🌐 Removed: skipTaskbar on Linux

在 X11 上,skipTaskbar 会向 X11 窗口管理器发送 _NET_WM_STATE_SKIP_TASKBAR 消息。Wayland 没有直接对应的方法,已知的解决方法有不可接受的权衡(例如,在 GNOME 中使用 Window.is_skip_taskbar 需要不安全模式),因此 Electron 无法在 Linux 上支持此功能。

🌐 On X11, skipTaskbar sends a _NET_WM_STATE_SKIP_TASKBAR message to the X11 window manager. There is not a direct equivalent for Wayland, and the known workarounds have unacceptable tradeoffs (e.g. Window.is_skip_taskbar in GNOME requires unsafe mode), so Electron is unable to support this feature on Linux.

API 已更改:session.setDevicePermissionHandler(handler)

🌐 API Changed: session.setDevicePermissionHandler(handler)

当使用 session.setDevicePermissionHandler(handler) 时调用的处理程序,其参数发生了变化。该处理程序不再传递一个 WebFrameMain 帧,而是传递 origin,它是正在检查设备权限的源。

🌐 The handler invoked when session.setDevicePermissionHandler(handler) is used has a change to its arguments. This handler no longer is passed a frame WebFrameMain, but instead is passed the origin, which is the origin that is checking for device permission.

计划中的重大 API 更改 (19.0)

🌐 Planned Breaking API Changes (19.0)

已移除:IA32 Linux 二进制文件

🌐 Removed: IA32 Linux binaries

这是由于 Chromium 102.0.4999.0 停止支持 IA32 Linux 所导致的。 这标志着 IA32 Linux 支持的移除 的完成。

🌐 This is a result of Chromium 102.0.4999.0 dropping support for IA32 Linux. This concludes the removal of support for IA32 Linux.

计划中的重大 API 更改 (18.0)

🌐 Planned Breaking API Changes (18.0)

已移除:nativeWindowOpen

🌐 Removed: nativeWindowOpen

在 Electron 15 之前,window.open 默认被修改为使用 BrowserWindowProxy。这意味着 window.open('about:blank') 无法同步打开可脚本化的子窗口,以及其他一些不兼容情况。自 Electron 15 起,nativeWindowOpen 已默认启用。

🌐 Prior to Electron 15, window.open was by default shimmed to use BrowserWindowProxy. This meant that window.open('about:blank') did not work to open synchronously scriptable child windows, among other incompatibilities. Since Electron 15, nativeWindowOpen has been enabled by default.

有关更多详细信息,请参阅 Electron 中的 window.open 文档

🌐 See the documentation for window.open in Electron for more details.

计划中的重大 API 更改 (17.0)

🌐 Planned Breaking API Changes (17.0)

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

🌐 Removed: desktopCapturer.getSources in the renderer

desktopCapturer.getSources API 现在仅在主进程中可用。为了提高 Electron 应用的默认安全性,这一行为已被更改。

🌐 The desktopCapturer.getSources API is now only available in the main process. This has been changed in order to improve the default security of Electron apps.

如果你需要此功能,可以按如下方式替换:

🌐 If you need this functionality, it can be replaced as follows:

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

然而,你应该考虑进一步限制返回给渲染器的信息;例如,向用户显示一个来源选择器,并且只返回用户选择的来源。

🌐 However, you should consider further restricting the information returned to the renderer; for instance, displaying a source selector to the user and only returning the selected source.

已弃用:nativeWindowOpen

🌐 Deprecated: nativeWindowOpen

在 Electron 15 之前,window.open 默认被修改为使用 BrowserWindowProxy。这意味着 window.open('about:blank') 无法同步打开可脚本化的子窗口,以及其他一些不兼容情况。自 Electron 15 起,nativeWindowOpen 已默认启用。

🌐 Prior to Electron 15, window.open was by default shimmed to use BrowserWindowProxy. This meant that window.open('about:blank') did not work to open synchronously scriptable child windows, among other incompatibilities. Since Electron 15, nativeWindowOpen has been enabled by default.

有关更多详细信息,请参阅 Electron 中的 window.open 文档

🌐 See the documentation for window.open in Electron for more details.

计划中的重大 API 更改 (16.0)

🌐 Planned Breaking API Changes (16.0)

行为更改:crashReporter 实现已在 Linux 上切换为 Crashpad

🌐 Behavior Changed: crashReporter implementation switched to Crashpad on Linux

Linux 上 crashReporter API 的底层实现已从 Breakpad 改为 Crashpad,使其与 Windows 和 Mac 保持一致。因此,现在会自动监控子进程,在 Node 子进程中调用 process.crashReporter.start 已不再必要(且不建议调用,因为这会启动第二个 Crashpad 报告实例)。

🌐 The underlying implementation of the crashReporter API on Linux has changed from Breakpad to Crashpad, bringing it in line with Windows and Mac. As a result of this, child processes are now automatically monitored, and calling process.crashReporter.start in Node child processes is no longer needed (and is not advisable, as it will start a second instance of the Crashpad reporter).

在 Linux 上,注释的报告方式也有一些细微的变化,包括长值将不再在附加了 __1__2 等的注释之间拆分,而是会在(新的、更长的)注释值限制处被截断。

🌐 There are also some subtle changes to how annotations will be reported on Linux, including that long values will no longer be split between annotations appended with __1, __2 and so on, and instead will be truncated at the (new, longer) annotation value limit.

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

🌐 Deprecated: desktopCapturer.getSources in the renderer

渲染器中 desktopCapturer.getSources API 的使用已被弃用,并将被移除。此更改将提升 Electron 应用的默认安全性。

🌐 Usage of the desktopCapturer.getSources API in the renderer has been deprecated and will be removed. This change improves the default security of Electron apps.

详情请参见这里,了解如何在你的应用中替换此 API。

🌐 See here for details on how to replace this API in your app.

计划中的重大 API 更改 (15.0)

🌐 Planned Breaking API Changes (15.0)

默认已更改:nativeWindowOpen 默认值为 true

🌐 Default Changed: nativeWindowOpen defaults to true

在 Electron 15 之前,window.open 默认被修改为使用 BrowserWindowProxy。这意味着 window.open('about:blank') 无法同步打开可脚本化的子窗口,以及其他一些不兼容情况。nativeWindowOpen 不再是实验性的,现在已成为默认设置。

🌐 Prior to Electron 15, window.open was by default shimmed to use BrowserWindowProxy. This meant that window.open('about:blank') did not work to open synchronously scriptable child windows, among other incompatibilities. nativeWindowOpen is no longer experimental, and is now the default.

有关更多详细信息,请参阅 Electron 中的 window.open 文档

🌐 See the documentation for window.open in Electron for more details.

已弃用:app.runningUnderRosettaTranslation

🌐 Deprecated: app.runningUnderRosettaTranslation

app.runningUnderRosettaTranslation 属性已被弃用。请使用 app.runningUnderARM64Translation

🌐 The app.runningUnderRosettaTranslation property has been deprecated. Use app.runningUnderARM64Translation instead.

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

计划中的重大 API 更改 (14.0)

🌐 Planned Breaking API Changes (14.0)

已移除:remote 模块

🌐 Removed: remote module

remote 模块在 Electron 12 中已被弃用,并将在 Electron 14 中移除。它已被 @electron/remote 模块取代。

🌐 The remote module was deprecated in Electron 12, and will be removed in Electron 14. It is replaced by the @electron/remote module.

// 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

🌐 Removed: app.allowRendererProcessReuse

app.allowRendererProcessReuse 属性将被移除,作为我们计划的一部分,以更紧密地与 Chromium 的安全性、性能和可维护性进程模型保持一致。

🌐 The app.allowRendererProcessReuse property will be removed as part of our plan to more closely align with Chromium's process model for security, performance and maintainability.

有关详细信息,请参见 #18397

🌐 For more detailed information see #18397.

已移除:浏览器窗口关联

🌐 Removed: Browser Window Affinity

在构建新的 BrowserWindow 时,affinity 选项将被移除,这是我们计划的一部分,旨在使安全性、性能和可维护性更紧密地与 Chromium 的进程模型对齐。

🌐 The affinity option when constructing a new BrowserWindow will be removed as part of our plan to more closely align with Chromium's process model for security, performance and maintainability.

有关详细信息,请参见 #18397

🌐 For more detailed information see #18397.

API 已更改:window.open()

🌐 API Changed: window.open()

可选参数 frameName 将不再设置窗口标题。现在,它遵循原生文档中对应参数 windowName 描述的规范。

🌐 The optional parameter frameName will no longer set the title of the window. This now follows the specification described by the native documentation under the corresponding parameter windowName.

如果你使用此参数来设置窗口的标题,可以改用 win.setTitle(title)

🌐 If you were using this parameter to set the title of a window, you can instead use win.setTitle(title).

已移除:worldSafeExecuteJavaScript

🌐 Removed: worldSafeExecuteJavaScript

在 Electron 14 中,worldSafeExecuteJavaScript 将被移除。没有替代方案,请确保你的代码在启用此属性的情况下仍能正常工作。自 Electron 12 起,它已默认启用。

🌐 In Electron 14, worldSafeExecuteJavaScript will be removed. There is no alternative, please ensure your code works with this property enabled. It has been enabled by default since Electron 12.

如果你使用 webFrame.executeJavaScriptwebFrame.executeJavaScriptInIsolatedWorld,将会受到此更改的影响。你需要确保这两种方法返回的值被 Context Bridge API 支持,因为这些方法使用相同的值传递语义。

🌐 You will be affected by this change if you use either webFrame.executeJavaScript or webFrame.executeJavaScriptInIsolatedWorld. You will need to ensure that values returned by either of those methods are supported by the Context Bridge API as these methods use the same value passing semantics.

已移除:BrowserWindowConstructorOptions 继承自父窗口

🌐 Removed: BrowserWindowConstructorOptions inheriting from parent windows

在 Electron 14 之前,使用 window.open 打开的窗口会继承其父窗口的 BrowserWindow 构造选项,例如 transparentresizable。从 Electron 14 开始,这种行为被移除,窗口将不会继承任何父窗口的 BrowserWindow 构造选项。

🌐 Prior to Electron 14, windows opened with window.open would inherit BrowserWindow constructor options such as transparent and resizable from their parent window. Beginning with Electron 14, this behavior is removed, and windows will not inherit any BrowserWindow constructor options from their parents.

相反,可以使用 setWindowOpenHandler 显式设置新窗口的选项:

🌐 Instead, explicitly set options for the new window with setWindowOpenHandler:

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

已移除:additionalFeatures

🌐 Removed: additionalFeatures

WebContents 的 new-windowdid-create-window 事件中已移除不推荐使用的 additionalFeatures 属性。由于 new-window 使用位置参数,该参数仍然存在,但始终将是空数组 []。(但请注意,new-window 事件本身已被弃用,并由 setWindowOpenHandler 取代。)窗口特性中的裸键现在将在选项对象中显示为值为 true 的键。

🌐 The deprecated additionalFeatures property in the new-window and did-create-window events of WebContents has been removed. Since new-window uses positional arguments, the argument is still present, but will always be the empty array []. (Though note, the new-window event itself is deprecated, and is replaced by setWindowOpenHandler.) Bare keys in window features will now present as keys with the value true in the options object.

// 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)

🌐 Planned Breaking API Changes (13.0)

API 已更改:session.setPermissionCheckHandler(handler)

🌐 API Changed: session.setPermissionCheckHandler(handler)

handler 方法的第一个参数以前总是 webContents,现在有时也可以是 null。你应该使用 requestingOriginembeddingOriginsecurityOrigin 属性来正确应对权限检查。由于 webContents 可能是 null,因此不能再依赖它。

🌐 The handler methods first parameter was previously always a webContents, it can now sometimes be null. You should use the requestingOrigin, embeddingOrigin and securityOrigin properties to respond to the permission check correctly. As the webContents can be null it can no longer be relied on.

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

🌐 Removed: shell.moveItemToTrash()

已弃用的同步 shell.moveItemToTrash() API 已被移除。请改用异步 shell.trashItem()

🌐 The deprecated synchronous shell.moveItemToTrash() API has been removed. Use the asynchronous shell.trashItem() instead.

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

已移除:BrowserWindow 扩展 API

🌐 Removed: BrowserWindow extension APIs

已弃用的扩展 API 已被删除:

🌐 The deprecated extension APIs have been removed:

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

请改用会话 API:

🌐 Use the session APIs instead:

  • 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 中的方法

🌐 Removed: methods in systemPreferences

以下 systemPreferences 方法已被弃用:

🌐 The following systemPreferences methods have been deprecated:

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

请改用以下 nativeTheme 属性:

🌐 Use the following nativeTheme properties instead:

  • 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 事件

🌐 Deprecated: WebContents new-window event

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

🌐 The new-window event of WebContents has been deprecated. It is replaced by webContents.setWindowOpenHandler().

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

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

计划中的重大 API 更改 (12.0)

🌐 Planned Breaking API Changes (12.0)

已移除:Pepper Flash 支持

🌐 Removed: Pepper Flash support

Chromium 已经移除了对 Flash 的支持,因此我们也必须跟进。详细信息请参见 Chromium 的 Flash 路线图

🌐 Chromium has removed support for Flash, and so we must follow suit. See Chromium's Flash Roadmap for more details.

默认已更改:worldSafeExecuteJavaScript 默认值为 true

🌐 Default Changed: worldSafeExecuteJavaScript defaults to true

在 Electron 12 中,worldSafeExecuteJavaScript 将默认启用。要恢复以前的行为,必须在 WebPreferences 中指定 worldSafeExecuteJavaScript: false。请注意,将此选项设置为 false不安全的

🌐 In Electron 12, worldSafeExecuteJavaScript will be enabled by default. To restore the previous behavior, worldSafeExecuteJavaScript: false must be specified in WebPreferences. Please note that setting this option to false is insecure.

此选项将在 Electron 14 中被移除,请迁移你的代码以支持默认值。

🌐 This option will be removed in Electron 14 so please migrate your code to support the default value.

默认已更改:contextIsolation 默认值为 true

🌐 Default Changed: contextIsolation defaults to true

在 Electron 12 中,contextIsolation 将默认启用。要恢复以前的行为,必须在 WebPreferences 中指定 contextIsolation: false

🌐 In Electron 12, contextIsolation will be enabled by default. To restore the previous behavior, contextIsolation: false must be specified in WebPreferences.

我们建议启用 contextIsolation以保障你的应用的安全。

🌐 We recommend having contextIsolation enabled for the security of your application.

另一个含义是,除非 nodeIntegrationtruecontextIsolationfalse,否则 require() 不能在渲染进程中使用。

🌐 Another implication is that require() cannot be used in the renderer process unless nodeIntegration is true and contextIsolation is false.

更多详情请参见: https://github.com/electron/electron/issues/23506

🌐 For more details see: https://github.com/electron/electron/issues/23506

已移除:crashReporter.getCrashesDirectory()

🌐 Removed: crashReporter.getCrashesDirectory()

crashReporter.getCrashesDirectory 方法已被移除。应该使用 app.getPath('crashDumps') 进行替代。

🌐 The crashReporter.getCrashesDirectory method has been removed. Usage should be replaced by app.getPath('crashDumps').

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

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

🌐 Removed: crashReporter methods in the renderer process

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

🌐 The following crashReporter methods are no longer available in the renderer process:

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

它们应该只从主进程中调用。

🌐 They should be called only from the main process.

详情请参见 #23265

🌐 See #23265 for more details.

默认已更改:crashReporter.start({ compress: true })

🌐 Default Changed: crashReporter.start({ compress: true })

compress 选项的默认值已从 false 更改为 true。这意味着崩溃转储将使用 Content-Encoding: gzip 头上传到崩溃接收服务器,并且其内容将被压缩。

🌐 The default value of the compress option to crashReporter.start has changed from false to true. This means that crash dumps will be uploaded to the crash ingestion server with the Content-Encoding: gzip header, and the body will be compressed.

如果你的崩溃采集服务器不支持压缩负载,你可以通过在崩溃报告器选项中指定 { compress: false } 来关闭压缩。

🌐 If your crash ingestion server does not support compressed payloads, you can turn off compression by specifying { compress: false } in the crash reporter options.

已弃用:remote 模块

🌐 Deprecated: remote module

remote 模块在 Electron 12 中已被弃用,并将在 Electron 14 中移除。它已被 @electron/remote 模块取代。

🌐 The remote module is deprecated in Electron 12, and will be removed in Electron 14. It is replaced by the @electron/remote module.

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

🌐 Deprecated: shell.moveItemToTrash()

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

🌐 The synchronous shell.moveItemToTrash() has been replaced by the new, asynchronous shell.trashItem().

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

计划中的重大 API 更改 (11.0)

🌐 Planned Breaking API Changes (11.0)

已移除:BrowserViewBrowserView.{destroy, fromId, fromWebContents, getAllViews}id 属性

🌐 Removed: BrowserView.{destroy, fromId, fromWebContents, getAllViews} and id property of BrowserView

实验性 APIs BrowserView.{destroy, fromId, fromWebContents, getAllViews} 已被移除。此外,BrowserViewid 属性也已被移除。

🌐 The experimental APIs BrowserView.{destroy, fromId, fromWebContents, getAllViews} have now been removed. Additionally, the id property of BrowserView has also been removed.

有关更详细的信息,请参见 #23578

🌐 For more detailed information, see #23578.

计划中的重大 API 更改 (10.0)

🌐 Planned Breaking API Changes (10.0)

已弃用:companyName 参数用于 crashReporter.start()

🌐 Deprecated: companyName argument to crashReporter.start()

crashReporter.start()companyName 参数以前是必需的,现在是可选的,此外,它已被弃用。要以非弃用的方式获得相同的行为,你可以在 globalExtra 中传递一个 companyName 值。

🌐 The companyName argument to crashReporter.start(), which was previously required, is now optional, and further, is deprecated. To get the same behavior in a non-deprecated way, you can pass a companyName value in globalExtra.

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

已弃用:crashReporter.getCrashesDirectory()

🌐 Deprecated: crashReporter.getCrashesDirectory()

crashReporter.getCrashesDirectory 方法已被弃用。应该使用 app.getPath('crashDumps') 进行替代。

🌐 The crashReporter.getCrashesDirectory method has been deprecated. Usage should be replaced by app.getPath('crashDumps').

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

已弃用:渲染器进程中的 crashReporter 方法

🌐 Deprecated: crashReporter methods in the renderer process

在渲染进程中调用以下 crashReporter 方法已不推荐使用:

🌐 Calling the following crashReporter methods from the renderer process is deprecated:

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

在渲染器的 crashReporter 模块中,唯一未被弃用的方法是 addExtraParameterremoveExtraParametergetParameters

🌐 The only non-deprecated methods remaining in the crashReporter module in the renderer are addExtraParameter, removeExtraParameter and getParameters.

从主进程调用时,所有上述方法均未弃用。

🌐 All above methods remain non-deprecated when called from the main process.

详情请参见 #23265

🌐 See #23265 for more details.

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

🌐 Deprecated: crashReporter.start({ compress: false })

crashReporter.start 中设置 { compress: false } 已被弃用。几乎所有崩溃收集服务器都支持 gzip 压缩。此选项将在未来的 Electron 版本中移除。

🌐 Setting { compress: false } in crashReporter.start is deprecated. Nearly all crash ingestion servers support gzip compression. This option will be removed in a future version of Electron.

默认已更改:enableRemoteModule 默认值为 false

🌐 Default Changed: enableRemoteModule defaults to false

在 Electron 9 中,如果不通过 enableRemoteModule WebPreferences 选项显式启用,使用 remote 模块就会开始发出警告。在 Electron 10 中,remote 模块默认已被禁用。要使用 remote 模块,必须在 WebPreferences 中指定 enableRemoteModule: true

🌐 In Electron 9, using the remote module without explicitly enabling it via the enableRemoteModule WebPreferences option began emitting a warning. In Electron 10, the remote module is now disabled by default. To use the remote module, enableRemoteModule: true must be specified in WebPreferences:

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

我们建议弃用远程模块

🌐 We recommend moving away from the remote module.

protocol.unregisterProtocol

protocol.uninterceptProtocol

API 现在是同步的,不再需要可选的回调。

🌐 The APIs are now synchronous and the optional callback is no longer needed.

// 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 现在是同步的,不再需要可选的回调。

🌐 The APIs are now synchronous and the optional callback is no longer needed.

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

已注册或拦截的协议在导航发生之前不会对当前页面生效。

🌐 The registered or intercepted protocol does not have effect on current page until navigation happens.

protocol.isProtocolHandled

此 API 已被弃用,用户应改用 protocol.isProtocolRegisteredprotocol.isProtocolIntercepted

🌐 This API is deprecated and users should use protocol.isProtocolRegistered and protocol.isProtocolIntercepted instead.

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

计划中的重大 API 更改 (9.0)

🌐 Planned Breaking API Changes (9.0)

默认已更改:在渲染进程中加载非上下文感知的本地模块默认被禁用

🌐 Default Changed: Loading non-context-aware native modules in the renderer process is disabled by default

从 Electron 9 开始,我们不允许在渲染进程中加载非上下文感知的本地模块。这是为了提高 Electron 项目的安全性、性能和可维护性。

🌐 As of Electron 9 we do not allow loading of non-context-aware native modules in the renderer process. This is to improve security, performance and maintainability of Electron as a project.

如果这对你有影响,你可以暂时将 app.allowRendererProcessReuse 设置为 false 来恢复旧的行为。这个标志只会在 Electron 11 之前作为一个选项存在,所以你应该计划将你的原生模块更新为上下文感知的模块。

🌐 If this impacts you, you can temporarily set app.allowRendererProcessReuse to false to revert to the old behavior. This flag will only be an option until Electron 11 so you should plan to update your native modules to be context aware.

有关详细信息,请参见 #18397

🌐 For more detailed information see #18397.

已弃用:BrowserWindow 扩展 API

🌐 Deprecated: BrowserWindow extension APIs

以下扩展 API 已被弃用:

🌐 The following extension APIs have been deprecated:

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

请改用会话 API:

🌐 Use the session APIs instead:

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

🌐 Removed: <webview>.getWebContents()

该 API 在 Electron 8.0 中已弃用,现已删除。

🌐 This API, which was deprecated in Electron 8.0, is now removed.

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

已移除:webFrame.setLayoutZoomLevelLimits()

🌐 Removed: webFrame.setLayoutZoomLevelLimits()

Chromium 已移除了更改布局缩放级别限制的支持,这已超出了 Electron 的维护能力。该功能在 Electron 8.x 中已被弃用,并在 Electron 9.x 中被移除。布局缩放级别限制现在固定为最小值 0.25 和最大值 5.0,如此处所定义。

🌐 Chromium has removed support for changing the layout zoom level limits, and it is beyond Electron's capacity to maintain it. The function was deprecated in Electron 8.x, and has been removed in Electron 9.x. The layout zoom level limits are now fixed at a minimum of 0.25 and a maximum of 5.0, as defined here.

行为更改:通过 IPC 发送非 JS 对象现在会抛出异常

🌐 Behavior Changed: Sending non-JS objects over IPC now throws an exception

在 Electron 8.0 中,IPC 被改为使用结构化克隆算法, 带来了显著的性能提升。为了帮助过渡, 旧的IPC序列化算法被保留并用于一些不属于的对象 可通过结构化克隆序列化。特别是,DOM 对象(例如 'Element', 'Location' 和 'DOMMatrix'),Node.js由 C++ 类支持的对象(例如 “process.env”,其中“Stream”的部分成员),以及由C++支持的Electron对象 类别(例如“WebContents”、“BrowserWindow”和“WebFrame”)则不存在 可通过结构化克隆序列化。每当调用旧算法时,a 已印出弃用警告。

🌐 In Electron 8.0, IPC was changed to use the Structured Clone Algorithm, bringing significant performance improvements. To help ease the transition, the old IPC serialization algorithm was kept and used for some objects that aren't serializable with Structured Clone. In particular, DOM objects (e.g. Element, Location and DOMMatrix), Node.js objects backed by C++ classes (e.g. process.env, some members of Stream), and Electron objects backed by C++ classes (e.g. WebContents, BrowserWindow and WebFrame) are not serializable with Structured Clone. Whenever the old algorithm was invoked, a deprecation warning was printed.

在 Electron 9.0 中,旧的序列化算法已被移除,发送此类不可序列化的对象现在会抛出“对象无法被克隆”错误。

🌐 In Electron 9.0, the old serialization algorithm has been removed, and sending such non-serializable objects will now throw an "object could not be cloned" error.

API 已更改:shell.openItem 现在是 shell.openPath

🌐 API Changed: shell.openItem is now shell.openPath

shell.openItem API 已被异步 shell.openPath API 取代。 你可以在这里查看原始的 API 提案和相关理由 here

🌐 The shell.openItem API has been replaced with an asynchronous shell.openPath API. You can see the original API proposal and reasoning here.

计划中的重大 API 更改 (8.0)

🌐 Planned Breaking API Changes (8.0)

行为更改:通过 IPC 发送的值现在使用结构化克隆算法进行序列化

🌐 Behavior Changed: Values sent over IPC are now serialized with Structured Clone Algorithm

用于序列化通过 IPC(通过 ipcRenderer.sendipcRenderer.sendSyncWebContents.send 及相关方法)发送的对象的算法,已从自定义算法切换为 V8 内置的 结构化克隆算法,这与用于序列化 postMessage 消息的算法相同。这为大消息带来了 2 倍的性能提升,但也带来了一些行为上的重大变化。

🌐 The algorithm used to serialize objects sent over IPC (through ipcRenderer.send, ipcRenderer.sendSync, WebContents.send and related methods) has been switched from a custom algorithm to V8's built-in Structured Clone Algorithm, the same algorithm used to serialize messages for postMessage. This brings about a 2x performance improvement for large messages, but also brings some breaking changes in behavior.

  • 通过 IPC 发送函数、Promises、WeakMaps、WeakSets 或包含任何此类值的对象现在将抛出异常,而不是静默地将函数转换为 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 传输。你可以通过封装底层 ArrayBufferUint8Array 转换回 Node.js Buffer:
Buffer.from(value.buffer, value.byteOffset, value.byteLength)

发送任何非原生 JS 类型的对象,例如 DOM 对象(如 ElementLocationDOMMatrix)、Node.js 对象(如 process.envStream)或 Electron 对象(如 WebContentsBrowserWindowWebFrame)已被弃用。在 Electron 8 中,这些对象仍会像以前一样被序列化,但会显示弃用警告信息;从 Electron 9 开始,发送这类对象将会抛出“无法克隆”错误。

🌐 Sending any objects that aren't native JS types, such as DOM objects (e.g. Element, Location, DOMMatrix), Node.js objects (e.g. process.env, Stream), or Electron objects (e.g. WebContents, BrowserWindow, WebFrame) is deprecated. In Electron 8, these objects will be serialized as before with a DeprecationWarning message, but starting in Electron 9, sending these kinds of objects will throw a 'could not be cloned' error.

已弃用:<webview>.getWebContents()

🌐 Deprecated: <webview>.getWebContents()

此 API 是使用 remote 模块实现的,该模块在性能和安全性方面都有影响。因此,应明确使用它。

🌐 This API is implemented using the remote module, which has both performance and security implications. Therefore its usage should be explicit.

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

然而,建议完全避免使用 remote 模块。

🌐 However, it is recommended to avoid using the remote module altogether.

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

🌐 Deprecated: webFrame.setLayoutZoomLevelLimits()

Chromium 已经移除了更改布局缩放级别限制的支持,而这超出了 Electron 的维护能力。该功能将在 Electron 8.x 中发出警告,并将在 Electron 9.x 中不再存在。布局缩放级别限制现在固定为最小 0.25 和最大 5.0,如此处所定义。

🌐 Chromium has removed support for changing the layout zoom level limits, and it is beyond Electron's capacity to maintain it. The function will emit a warning in Electron 8.x, and cease to exist in Electron 9.x. The layout zoom level limits are now fixed at a minimum of 0.25 and a maximum of 5.0, as defined here.

systemPreferences 中已弃用的事件

🌐 Deprecated events in systemPreferences

以下 systemPreferences 事件已被弃用:

🌐 The following systemPreferences events have been deprecated:

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

请改用 nativeTheme 模块上的新 updated 事件。

🌐 Use the new updated event on the nativeTheme module instead.

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

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

已弃用:systemPreferences 中的方法

🌐 Deprecated: methods in systemPreferences

以下 systemPreferences 方法已被弃用:

🌐 The following systemPreferences methods have been deprecated:

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

请改用以下 nativeTheme 属性:

🌐 Use the following nativeTheme properties instead:

  • 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)

🌐 Planned Breaking API Changes (7.0)

已弃用:Atom.io Node 头文件 URL

🌐 Deprecated: Atom.io Node Headers URL

这是在 .npmrc 文件中指定为 disturl 的 URL,或者在构建本地 Node 模块时作为 --dist-url 命令行标志的 URL。两者在可预见的未来都将被支持,但建议你进行切换。

🌐 This is the URL specified as disturl in a .npmrc file or as the --dist-url command line flag when building native Node modules. Both will be supported for the foreseeable future but it is recommended that you switch.

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

🌐 Deprecated: https://atom.io/download/electron

替换为:https://electron.nodejs.cn/headers

🌐 Replace with: https://electron.nodejs.cn/headers

API 已更改:session.clearAuthCache() 不再接受选项

🌐 API Changed: session.clearAuthCache() no longer accepts options

session.clearAuthCache API 不再接受清除选项,而是无条件地清空整个缓存。

🌐 The session.clearAuthCache API no longer accepts options for what to clear, and instead unconditionally clears the whole cache.

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

API 已更改:powerMonitor.querySystemIdleState 现在是 powerMonitor.getSystemIdleState

🌐 API Changed: powerMonitor.querySystemIdleState is now 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

🌐 API Changed: powerMonitor.querySystemIdleTime is now powerMonitor.getSystemIdleTime

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

API 已更改:webFrame.setIsolatedWorldInfo 替代了独立方法

🌐 API Changed: webFrame.setIsolatedWorldInfo replaces separate methods

// 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 属性

🌐 Removed: marked property on getBlinkMemoryInfo

此属性在 Chromium 77 中被删除,因此不再可用。

🌐 This property was removed in Chromium 77, and as such is no longer available.

行为更改:<input type="file"/>webkitdirectory 属性现在列出目录内容

🌐 Behavior Changed: webkitdirectory attribute for <input type="file"/> now lists directory contents

HTML 文件输入中的 webkitdirectory 属性允许它们选择文件夹。Electron 的早期版本中实现不正确,输入的 event.target.files 返回了一个 FileList,而该 FileList 返回一个与所选文件夹对应的 File

🌐 The webkitdirectory property on HTML file inputs allows them to select folders. Previous versions of Electron had an incorrect implementation where the event.target.files of the input returned a FileList that returned one File corresponding to the selected folder.

从 Electron 7 开始,FileList 现在是包含该文件夹中所有文件的列表,类似于 Chrome、Firefox 和 Edge (MDN 文档链接)。

🌐 As of Electron 7, that FileList is now list of all files contained within the folder, similarly to Chrome, Firefox, and Edge (link to MDN docs).

作为说明,采用具有以下结构的文件夹:

🌐 As an illustration, take a folder with this structure:

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

在 Electron ≤6 中,这将返回一个带有 File 对象的 FileList,用于:

🌐 In Electron <=6, this would return a FileList with a File object for:

path/to/folder

在 Electron 7 中,这现在返回一个带有 File 对象的 FileList 用于:

🌐 In Electron 7, this now returns a FileList with a File object for:

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

请注意,webkitdirectory 不再提供所选文件夹的路径。如果你需要的是所选文件夹的路径而不是文件夹内容,请参阅 dialog.showOpenDialog API(链接)。

🌐 Note that webkitdirectory no longer exposes the path to the selected folder. If you require the path to the selected folder rather than the folder contents, see the dialog.showOpenDialog API (link).

API 已更改:基于回调的 Promisify API 版本

🌐 API Changed: Callback-based versions of promisified APIs

Electron 5 和 Electron 6 引入了基于 Promise 的现有异步 API,并弃用了旧的基于回调的对应 API。在 Electron 7 中,所有已弃用的基于回调的 API 都已被移除。

🌐 Electron 5 and Electron 6 introduced Promise-based versions of existing asynchronous APIs and deprecated their older, callback-based counterparts. In Electron 7, all deprecated callback-based APIs are now removed.

这些函数现在只返回 Promise:

🌐 These functions now only return Promises:

  • 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 的异步:

🌐 These functions now have two forms, synchronous and Promise-based asynchronous:

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

计划中的重大 API 更改 (6.0)

🌐 Planned Breaking API Changes (6.0)

API 已更改:win.setMenu(null) 现在是 win.removeMenu()

🌐 API Changed: win.setMenu(null) is now win.removeMenu()

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

API 已更改:渲染进程中的 electron.screen 应通过 remote 访问

🌐 API Changed: electron.screen in the renderer process should be accessed via remote

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

API 更改:在沙箱渲染器中 require() 节点内置不再会隐式加载 remote 版本

🌐 API Changed: require()ing node builtins in sandboxed renderers no longer implicitly loads the remote version

// 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 replaced with powerMonitor.getSystemIdleState

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

已弃用:powerMonitor.querySystemIdleTime 已被 powerMonitor.getSystemIdleTime 替代

🌐 Deprecated: powerMonitor.querySystemIdleTime replaced with powerMonitor.getSystemIdleTime

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

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

🌐 Deprecated: app.enableMixedSandbox() is no longer needed

// Deprecated
app.enableMixedSandbox()

现在默认启用混合沙盒模式。

🌐 Mixed-sandbox mode is now enabled by default.

已弃用:Tray.setHighlightMode

🌐 Deprecated: Tray.setHighlightMode

在 macOS Catalina 下,我们以前的托盘实现无法正常工作。苹果的原生替代方案不支持更改高亮显示行为。

🌐 Under macOS Catalina our former Tray implementation breaks. Apple's native substitute doesn't support changing the highlighting behavior.

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

计划中的重大 API 更改 (5.0)

🌐 Planned Breaking API Changes (5.0)

默认已更改:nodeIntegrationwebviewTag 默认为 false,contextIsolation 默认为 true

🌐 Default Changed: nodeIntegration and webviewTag default to false, contextIsolation defaults to true

以下 webPreferences 选项的默认值已被弃用,请使用下面列出的新默认值。

🌐 The following webPreferences option default values are deprecated in favor of the new defaults listed below.

属性过时的默认值新默认值
contextIsolationfalsetrue
nodeIntegrationtruefalse
webviewTag如果已设置则为 nodeIntegration,否则为 truefalse

例如,重新启用 webviewTag

🌐 E.g. Re-enabling the webviewTag

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

行为已更改:通过 nativeWindowOpen 打开的子窗口中的 nodeIntegration

🌐 Behavior Changed: nodeIntegration in child windows opened via nativeWindowOpen

使用 nativeWindowOpen 选项打开的子窗口将始终禁用 Node.js 集成,除非 nodeIntegrationInSubFramestrue

🌐 Child windows opened with the nativeWindowOpen option will always have Node.js integration disabled, unless nodeIntegrationInSubFrames is true.

API 已更改:现在必须在应用准备好之前注册特权方案

🌐 API Changed: Registering privileged schemes must now be done before app ready

渲染进程 API webFrame.registerURLSchemeAsPrivilegedwebFrame.registerURLSchemeAsBypassingCSP 以及浏览器进程 API protocol.registerStandardSchemes 已被移除。
新增了一个 API protocol.registerSchemesAsPrivileged,应使用它来注册具有必要权限的自定义方案。自定义方案必须在应用准备好之前注册。

🌐 Renderer process APIs webFrame.registerURLSchemeAsPrivileged and webFrame.registerURLSchemeAsBypassingCSP as well as browser process API protocol.registerStandardSchemes have been removed. A new API, protocol.registerSchemesAsPrivileged has been added and should be used for registering custom schemes with the required privileges. Custom schemes are required to be registered before app ready.

已弃用:webFrame.setIsolatedWorld* 已被 webFrame.setIsolatedWorldInfo 替代

🌐 Deprecated: webFrame.setIsolatedWorld* replaced with 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 现在接受异步回调

🌐 API Changed: webFrame.setSpellCheckProvider now takes an asynchronous callback

spellCheck 回调现在是异步的,autoCorrectWord 参数已被移除。

🌐 The spellCheck callback is now asynchronous, and autoCorrectWord parameter has been removed.

// 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 现在是同步的

🌐 API Changed: webContents.getZoomLevel and webContents.getZoomFactor are now synchronous

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)

🌐 Planned Breaking API Changes (4.0)

以下列表包括 Electron 4.0 中的重大 API 更改。

🌐 The following list includes the breaking API changes made in Electron 4.0.

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(默认就是 true)。如果该钩子不存在,本地模块将在 Windows 上加载失败,并出现类似 Cannot find module 的错误信息。有关更多信息,请参阅 本地模块指南

🌐 When building native modules for windows, the win_delay_load_hook variable in the module's binding.gyp must be true (which is the default). If this hook is not present, then the native module will fail to load on Windows, with an error message like Cannot find module. See the native module guide for more.

已移除:IA32 Linux 支持

🌐 Removed: IA32 Linux support

Electron 18 将不再支持在 32 位 Linux 系统上运行。有关更多信息,请参阅 停止支持 32 位 Linux

🌐 Electron 18 will no longer run on 32-bit Linux systems. See discontinuing support for 32-bit Linux for more information.

重大 API 更改 (3.0)

🌐 Breaking API Changes (3.0)

以下列表包括 Electron 3.0 中的重大 API 更改。

🌐 The following list includes the breaking API changes in Electron 3.0.

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 标头 URL

🌐 Node Headers URL

这是在 .npmrc 文件中指定为 disturl 的 URL,或在构建本地 Node 模块时作为 --dist-url 命令行标志指定的 URL。

🌐 This is the URL specified as disturl in a .npmrc file or as the --dist-url command line flag when building native Node modules.

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

🌐 Deprecated: https://atom.io/download/atom-shell

替换为:https://atom.io/download/electron

🌐 Replace with: https://atom.io/download/electron

重大 API 更改 (2.0)

🌐 Breaking API Changes (2.0)

以下列表包括 Electron 2.0 中的重大 API 更改。

🌐 The following list includes the breaking API changes made in Electron 2.0.

autoUpdater

// Deprecated
autoUpdater.setFeedURL(url, headers)
// Replace with
autoUpdater.setFeedURL({
url,
headers
})

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 资源

🌐 Duplicate ARM Assets

每个 Electron 版本都包含两个文件名略有不同的相同 ARM 构建版本,例如 electron-v1.7.3-linux-arm.zipelectron-v1.7.3-linux-armv7l.zip。带有 v7l 前缀的资源是为了向用户说明它支持的是哪个 ARM 版本,并将其与将来可能生成的 armv6l 和 arm64 资源区分开来。

🌐 Each Electron release includes two identical ARM builds with slightly different filenames, like electron-v1.7.3-linux-arm.zip and electron-v1.7.3-linux-armv7l.zip. The asset with the v7l prefix was added to clarify to users which ARM version it supports, and to disambiguate it from future armv6l and arm64 assets that may be produced.

不带前缀的文件仍然会被发布,以避免破坏可能正在使用它的任何设置。从 2.0 开始,不带前缀的文件将不再发布。

🌐 The file without the prefix is still being published to avoid breaking any setups that may be consuming it. Starting at 2.0, the unprefixed file will no longer be published.

详情请参见 69867189

🌐 For details, see 6986 and 7189.