破坏性变更
重大变更将在本文档中进行记录,并尽可能在 JavaScript 代码中添加弃用警告,至少在更改发生前一个主要版本。
重大变更类型
本文档使用以下约定来对重大变更进行分类
- API 已更改: API 已更改,导致未更新的代码必然会抛出异常。
- 行为已更改: Electron 的行为已更改,但并非一定会抛出异常。
- 默认值已更改: 依赖旧默认值的代码可能会中断,不一定会抛出异常。可以通过显式指定值来恢复旧行为。
- 已弃用: API 已标记为弃用。该 API 将继续运行,但会发出弃用警告,并在未来的版本中移除。
- 已移除: API 或功能已被移除,不再受 Electron 支持。
计划中的重大 API 变更 (39.0)
已弃用:--host-rules 命令行开关
Chromium 正在弃用 --host-rules 开关。
您应该改用 --host-resolver-rules。
行为已更改:window.open 弹窗始终可调整大小
根据当前的 WHATWG 规范,window.open API 现在将始终创建可调整大小的弹窗。
要恢复以前的行为
webContents.setWindowOpenHandler((details) => {
return {
action: 'allow',
overrideBrowserWindowOptions: {
resizable: details.features.includes('resizable=yes')
}
}
})
行为变更:共享纹理 OSR paint 事件数据结构
在使用共享纹理离屏渲染功能时,paint 事件现在会发出一个更结构化的对象。它将 sharedTextureHandle、planes、modifier 移动到一个统一的 handle 属性中。有关更多详细信息,请参阅 OffscreenSharedTexture API 结构。
计划中的重大 API 变更 (38.0)
已移除:ELECTRON_OZONE_PLATFORM_HINT 环境变量
--ozone-platform 标志的默认值 已更改为 auto。
Electron 现在在 Wayland 会话中启动时(当 XDG_SESSION_TYPE=wayland 时)默认作为原生 Wayland 应用程序运行。用户可以通过传递 --ozone-platform=x11 来强制使用 XWayland。
已移除:ORIGINAL_XDG_CURRENT_DESKTOP 环境变量
以前,Electron 会在内部将 XDG_CURRENT_DESKTOP 的值更改为 Unity,并将桌面会话的原始名称存储在一个单独的变量中。XDG_CURRENT_DESKTOP 不再被覆盖,现在反映了实际的桌面环境。
已移除:macOS 11 支持
Chromium 不再支持 macOS 11 (Big Sur)。
旧版本的 Electron 将继续在 Big Sur 上运行,但运行 Electron v38.0.0 及更高版本需要 macOS 12 (Monterey) 或更高版本。
已移除:plugin-crashed 事件
webContents 中的 plugin-crashed 事件已移除。
已弃用:webFrame.routingId 属性
webFrame 对象中的 routingId 属性将被移除。
您应该使用 webFrame.frameToken 代替。
已弃用:webFrame.findFrameByRoutingId(routingId)
webFrame.findFrameByRoutingId(routingId) 函数将被移除。
您应该使用 webFrame.findFrameByToken(frameToken) 代替。
计划中的重大 API 变更 (37.0)
Utility Process 未处理的拒绝行为变更
现在,当发生未处理的拒绝时,Utility Process 将会发出一条错误消息警告,而不是使进程崩溃。
要恢复以前的行为,您可以使用
process.on('unhandledRejection', () => {
process.exit(1)
})
行为变更:process.exit() 同步终止实用程序进程
在实用工具进程中调用 process.exit() 现在将同步终止该进程。这使得 process.exit() 的行为与 Node.js 的行为保持一致。
请参阅 Node.js 文档和 PR #45690,以了解其潜在影响,例如在调用 console.log() 之前调用 process.exit() 时。
行为变更:WebUSB 和 WebSerial 黑名单支持
WebUSB 和 Web Serial 现在支持 Chromium 使用的 WebUSB 黑名单和 Web Serial 黑名单,并在各自的规范中列出。
要禁用这些功能,用户可以传递 disable-usb-blocklist 和 disable-serial-blocklist 作为命令行标志。
已移除:ProtocolResponse 中 session 属性的 null 值
这个已弃用的功能已被移除。
以前,将 ProtocolResponse.session 属性设置为 null 会创建一个随机的独立会话。这已不再受支持。
由于开销成本,不建议在此处使用单用途会话;但是,需要保留此行为的旧代码可以通过使用 session.fromPartition(some_random_string) 创建一个随机会话,然后在 ProtocolResponse.session 中使用它来模拟此行为。
行为变更:Linux 上 BrowserWindow.IsVisibleOnAllWorkspaces()
如果窗口当前不可见,BrowserWindow.IsVisibleOnAllWorkspaces() 现在在 Linux 上将返回 false。
计划中的重大 API 变更 (36.0)
行为变更:app.commandLine
app.commandLine 会将大写开关和参数转换为小写。
app.commandLine 最初仅用于处理 Chromium 开关(不区分大小写),并且通过 app.commandLine 传递的开关不会传递给任何子进程。
如果您曾使用 app.commandLine 来控制主进程的行为,现在应通过 process.argv 来实现。
已弃用:NativeImage.getBitmap()
NativeImage.toBitmap() 返回一个新分配的位图副本。NativeImage.getBitmap() 最初是一个返回原始位图而不是副本的替代函数。在引入沙箱后,这种情况发生了变化,因此两者都返回副本并且功能上等效。
客户端代码应调用 NativeImage.toBitmap()
// Deprecated
bitmap = image.getBitmap()
// Use this instead
bitmap = image.toBitmap()
已移除:PrinterInfo 上的 isDefault 和 status 属性
已从 PrinterInfo 对象中移除这些属性,因为它们已从上游 Chromium 中移除。
已移除:Session.clearStorageData(options) 中的 quota 类型 syncable
调用 Session.clearStorageData(options) 时,不再支持 options.quota 类型 syncable,因为它已被 移除。
已弃用:ProtocolResponse 中 session 属性的 null 值
以前,将 ProtocolResponse.session 属性设置为 null 会创建一个随机的独立会话。这不再受支持。
由于开销成本,不建议在此处使用单用途会话;但是,需要保留此行为的旧代码可以通过使用 session.fromPartition(some_random_string) 创建一个随机会话,然后在 ProtocolResponse.session 中使用它来模拟此行为。
已弃用:Session.clearStorageData(options) 中的 quota 属性
调用 Session.clearStorageData(options) 时,options.quota 属性已被弃用。由于 syncable 类型已被移除,现在只剩下一种类型——'temporary'——因此没有必要再指定它。
已弃用:session 上的扩展方法和事件
session.loadExtension、session.removeExtension、session.getExtension、session.getAllExtensions、'extension-loaded' 事件、'extension-unloaded' 事件和 'extension-ready' 事件已全部移至新的 session.extensions 类。
已移除:systemPreferences.isAeroGlassEnabled()
systemPreferences.isAeroGlassEnabled() 函数已被移除,没有替代方案。自 Electron 23 起,它一直返回 true,因为 Electron 23 及更高版本仅支持 Windows 10+,而 DWM 合成已无法禁用。
已更改:GTK 4 在运行 GNOME 时为默认值
在 上游更改之后,GTK 4 现在是运行 GNOME 时的默认设置。
在极少数情况下,这可能会导致某些应用程序或配置出错,并显示以下消息:
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 命令行标志来解决此问题:
$ electron --gtk-version=3 # or --gtk-version=2
同样的操作也可以通过 app.commandLine.appendSwitch 函数完成。
计划中的重大 API 变更 (35.0)
行为已更改:Linux 上 Dialog API 的 defaultPath 选项
在 Linux 上,文件对话框所需的 portal 版本已从 4 恢复到 3。使用 Dialog API 的 defaultPath 选项时,除非 portal 后端版本为 4 或更高,否则不支持。可以使用 --xdg-portal-required-version 命令行开关来强制为您的应用程序设置所需版本。有关更多详细信息,请参阅 #44426。
已弃用:session.serviceWorkers 上的 getFromVersionID
session.serviceWorkers.fromVersionID(versionId) API 已弃用,取而代之的是 session.serviceWorkers.getInfoFromVersionID(versionId)。此更改是为了在引入 session.serviceWorkers.getWorkerFromVersionID(versionId) API 后更清楚地说明返回的是哪个对象。
// Deprecated
session.serviceWorkers.fromVersionID(versionId)
// Replace with
session.serviceWorkers.getInfoFromVersionID(versionId)
已弃用:Session 上的 setPreloads、getPreloads
引入了 registerPreloadScript、unregisterPreloadScript 和 getPreloadScripts 作为已弃用方法的替代品。这些新 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')
})
已弃用:WebContents 上 console-message 事件中的 level、message、line 和 sourceId 参数
WebContents 上的 console-message 事件已更新,在 Event 参数中提供详细信息。
// Deprecated
webContents.on('console-message', (event, level, message, line, sourceId) => {})
// Replace with:
webContents.on('console-message', ({ level, message, lineNumber, sourceId, frame }) => {})
此外,level 现在是一个字符串,可能的值为 info、warning、error 和 debug。
行为变更:WebRequestFilter 的 urls 属性。
以前,空 urls 数组被解释为包含所有 URL。要明确包含所有 URL,开发人员现在应该使用 <all_urls> 模式,这是一个指定的 URL 模式,它匹配所有可能的 URL。此更改阐明了意图并确保了更可预测的行为。
// Deprecated
const deprecatedFilter = {
urls: []
}
// Replace with
const newFilter = {
urls: ['<all_urls>']
}
已弃用:systemPreferences.isAeroGlassEnabled()
systemPreferences.isAeroGlassEnabled() 函数已被弃用,没有替代品。自 Electron 23 起,它一直返回 true,因为 Electron 23 仅支持 Windows 10+,在这些系统中 DWM 合成已无法被禁用。
计划中的重大 API 变更 (34.0)
行为变更:在 Windows 全屏模式下,菜单栏将被隐藏
这使得行为与 Linux 保持一致。之前的行为:在 Windows 上全屏时菜单栏仍然可见。新的行为:在 Windows 上全屏时菜单栏隐藏。
更正:此项先前被列为 Electron 33 中的重大变更,但实际上是在 Electron 34 中首次发布的。
计划中的重大 API 变更 (33.0)
已弃用:document.execCommand("paste")
同步剪贴板读取 API document.execCommand("paste") 已被弃用,取而代之的是 异步剪贴板 API。这是为了与浏览器默认行为保持一致。
WebPreferences 上的 enableDeprecatedPaste 选项(用于触发此 API 的权限检查)以及相关的 deprecated-sync-clipboard-read 权限类型也已弃用。
行为已更改:frame 属性可能检索已分离的 WebFrameMain 实例或根本不检索
提供 WebFrameMain 实例访问权限的 API 可能会返回一个 frame.detached 设置为 true 的实例,或者可能返回 null。
当 frame 执行跨域导航时,它会进入分离状态,不再附加到页面。在此状态下,它可能在被删除之前运行 unload 处理程序。如果在该状态下发送 IPC,frame.detached 将被设置为 true,并且 frame 将很快被销毁。
接收事件时,请务必在接收到 WebFrameMain 属性后立即访问它们。否则,不能保证它指向与接收时相同的网页。为了避免预期不匹配,Electron 将在晚期访问(网页已更改)的情况下返回 null。
ipcMain.on('unload-event', (event) => {
event.senderFrame // ✅ accessed immediately
})
ipcMain.on('unload-event', async (event) => {
await crossOriginNavigationPromise
event.senderFrame // ❌ returns `null` due to late access
})
行为变更:Windows 上的自定义协议 URL 处理
由于 Chromium 进行了变更以支持 非特殊方案 URL,使用 Windows 文件路径的自定义协议 URL 将不再能正确地与已弃用的 protocol.registerFileProtocol 以及 BrowserWindow.loadURL、WebContents.loadURL 和 <webview>.loadURL 上的 baseURLForDataURL 属性配合使用。protocol.handle 也将无法与这些类型的 URL 一起使用,但这并不是一个变更,因为它一直都是这样工作的。
// No longer works
protocol.registerFileProtocol('other', () => {
callback({ filePath: '/path/to/my/file' })
})
const mainWindow = new BrowserWindow()
mainWindow.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: 'other://C:\\myapp' })
mainWindow.loadURL('other://C:\\myapp\\index.html')
// Replace with
const path = require('node:path')
const nodeUrl = require('node:url')
protocol.handle(other, (req) => {
const srcPath = 'C:\\myapp\\'
const reqURL = new URL(req.url)
return net.fetch(nodeUrl.pathToFileURL(path.join(srcPath, reqURL.pathname)).toString())
})
mainWindow.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: 'other://' })
mainWindow.loadURL('other://index.html')
行为变更:`app` 的 `login` 事件上的 `webContents` 属性
来自 app 的 login 事件中的 webContents 属性在为 utility process(使用 respondToAuthRequestsFromMainProcess 选项创建)的请求触发事件时将为 null。
已弃用:BrowserWindowConstructorOption.type 中的 textured 选项
BrowserWindowConstructorOptions 中 type 的 textured 选项已被弃用,没有替代方案。该选项依赖于 macOS 上的 NSWindowStyleMaskTexturedBackground 样式掩码,该掩码已被弃用且没有替代方案。
移除:对 macOS 10.15 的支持
Chromium 不再支持 macOS 10.15 (Catalina)。
旧版本的 Electron 将继续在 Catalina 上运行,但运行 Electron v33.0.0 及更高版本需要 macOS 11 (Big Sur) 或更高版本。
行为变更:原生模块现在需要 C++20
由于上游的变更,V8 和 Node.js 现在都需要 C++20 作为最低版本。使用原生 Node.js 模块的开发者应该使用 --std=c++20 而不是 --std=c++17 来编译他们的模块。使用 gcc9 或更低版本的图像可能需要更新到 gcc10 才能进行编译。有关更多详细信息,请参阅 #43555。
已弃用:systemPreferences.accessibilityDisplayShouldReduceTransparency
systemPreferences.accessibilityDisplayShouldReduceTransparency 属性现已废弃,推荐使用新的 nativeTheme.prefersReducedTransparency,它提供相同的信息并且可以跨平台工作。
// Deprecated
const shouldReduceTransparency = systemPreferences.accessibilityDisplayShouldReduceTransparency
// Replace with:
const prefersReducedTransparency = nativeTheme.prefersReducedTransparency
计划中的重大 API 变更 (32.0)
已移除:File.path
Web File 对象的非标准 path 属性在 Electron 的早期版本中被添加,作为处理原生文件的一种便捷方式,因为当时在渲染器中处理所有事情更为常见。然而,它偏离了标准并带来了一定的安全风险,因此自 Electron 32.0 起,它已被移除,取而代之的是 webUtils.getPathForFile 方法。
// Before (renderer)
const file = document.querySelector('input[type=file]').files[0]
alert(`Uploaded file path was: ${file.path}`)
// After (renderer)
const file = document.querySelector('input[type=file]').files[0]
electron.showFilePath(file)
// (preload)
const { contextBridge, webUtils } = require('electron')
contextBridge.exposeInMainWorld('electron', {
showFilePath (file) {
// It's best not to expose the full file path to the web content if
// possible.
const path = webUtils.getPathForFile(file)
alert(`Uploaded file path was: ${path}`)
}
})
已弃用:WebContents 上的 clearHistory、canGoBack、goBack、canGoForward、goForward、goToIndex、canGoToOffset、goToOffset
与导航相关的 API 现已弃用。
这些 API 已移至 WebContents 的 navigationHistory 属性,以提供更结构化和直观的界面来管理导航历史。
// 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 目录将被删除
如果您在 app.getPath('userData') 返回的目录中有一个名为 databases 的目录,它将在 Electron 32 首次运行时被删除。databases 目录曾被 WebSQL 使用,该功能已在 Electron 31 中移除。Chromium 现在执行一项清理操作,会删除此目录。请参阅问题 #45396。
计划中的重大 API 变更 (31.0)
已移除:WebSQL 支持
Chromium 已在上游移除 WebSQL 支持,并将其迁移到仅限 Android。有关更多信息,请参阅 Chromium 的移除意向讨论。
行为已更改:nativeImage.toDataURL 将保留 PNG 色彩空间
PNG 解码器实现已更改为保留色彩空间数据,此函数返回的编码数据现在与之匹配。
有关更多信息,请参阅 crbug.com/332584706。
行为已更改:macOS 上 window.flashFrame(bool) 将持续闪烁 Dock 图标
这使得行为与 Windows 和 Linux 保持一致。先前行为:第一个 flashFrame(true) 只会使 Dock 图标闪烁一次(使用 NSInformationalRequest 级别),而 flashFrame(false) 则不执行任何操作。新行为:持续闪烁直到调用 flashFrame(false)。这使用了 NSCriticalRequest 级别。要显式使用 NSInformationalRequest 引起 Dock 图标的一次弹跳,仍然可以使用 dock.bounce('informational')。
计划中的重大 API 变更 (30.0)
行为变更:跨域 iframe 现在使用权限策略访问功能
跨域 iframe 现在必须通过 allow 属性指定可用于给定 iframe 的功能,才能访问它们。
更多信息请参阅文档。
已移除:--disable-color-correct-rendering 开关
此开关从未正式文档化,但在此处仍记录其移除。Chromium 本身现在对色彩空间有更好的支持,因此不需要此标志。
行为变更:macOS 上 BrowserView.setAutoResize 的行为
在 Electron 30 中,BrowserView 现在是新的 WebContentsView API 的包装器。
之前,macOS 上的 BrowserView API 的 setAutoResize 函数是基于 autoresizing 实现的,而在 Windows 和 Linux 上则使用自定义算法。对于使 BrowserView 充满整个窗口等简单用例,这两种方法的行为是相同的。但是,在更复杂的场景下,BrowserView 在 macOS 上的 autoresize 方式与其他平台不同,因为 Windows 和 Linux 的自定义调整大小算法并未完全匹配 macOS 的 autoresizing API 的行为。现在,所有平台的 autoresize 行为已统一。
如果您的应用程序使用 BrowserView.setAutoResize 来执行比让 BrowserView 充满整个窗口更复杂的操作,那么您可能已经实现了自定义逻辑来处理 macOS 上的这种行为差异。如果是这样,在 Electron 30 中,由于 autoresize 行为已一致,这些自定义逻辑将不再需要。
已弃用:BrowserView
BrowserView 类已被弃用,取而代之的是新的 WebContentsView 类。
BrowserWindow 中的 BrowserView 相关方法也已被弃用。
BrowserWindow.fromBrowserView(browserView)
win.setBrowserView(browserView)
win.getBrowserView()
win.addBrowserView(browserView)
win.removeBrowserView(browserView)
win.setTopBrowserView(browserView)
win.getBrowserViews()
已移除:WebContents 上 context-menu 的 params.inputFormType 属性
WebContents 的 context-menu 事件中 params 对象的 inputFormType 属性已被移除。请改用新的 formControlType 属性。
已移除:process.getIOCounters()
Chromium 已移除对该信息的访问。
计划中的重大 API 变更 (29.0)
行为变更:ipcRenderer 不能再通过 contextBridge 发送
现在,尝试通过 contextBridge 将整个 ipcRenderer 模块作为对象发送将导致桥的接收端出现一个空对象。此更改是为了消除/缓解安全隐患。您不应该直接通过桥暴露 ipcRenderer 或其方法。相反,请提供一个如下所示的安全包装器
contextBridge.exposeInMainWorld('app', {
onEvent: (cb) => ipcRenderer.on('foo', (e, ...args) => cb(args))
})
已移除:app 上的 renderer-process-crashed 事件
app 上的 renderer-process-crashed 事件已被移除。请改用新的 render-process-gone 事件。
// Removed
app.on('renderer-process-crashed', (event, webContents, killed) => { /* ... */ })
// Replace with
app.on('render-process-gone', (event, webContents, details) => { /* ... */ })
已移除:WebContents 和 <webview> 上的 crashed 事件
WebContents 和 <webview> 上的 crashed 事件已被移除。请改用新的 render-process-gone 事件。
// Removed
win.webContents.on('crashed', (event, killed) => { /* ... */ })
webview.addEventListener('crashed', (event) => { /* ... */ })
// Replace with
win.webContents.on('render-process-gone', (event, details) => { /* ... */ })
webview.addEventListener('render-process-gone', (event) => { /* ... */ })
已移除:app 上的 gpu-process-crashed 事件
app 上的 gpu-process-crashed 事件已被移除。请改用新的 child-process-gone 事件。
// Removed
app.on('gpu-process-crashed', (event, killed) => { /* ... */ })
// Replace with
app.on('child-process-gone', (event, details) => { /* ... */ })
计划中的重大 API 变更 (28.0)
行为变更:将 WebContents.backgroundThrottling 设置为 false 会影响主机 BrowserWindow 中的所有 WebContents
将 WebContents.backgroundThrottling 设置为 false 将禁用 BrowserWindow 中所有由它显示的 WebContents 的帧节流。
移除: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()
已移除 BrowserWindow.getTrafficLightPosition(),应改用 BrowserWindow.getWindowButtonPosition() API,当没有自定义位置时,该 API 返回 null 而不是 { x: 0, y: 0 }。
// Removed in Electron 28
const pos = win.getTrafficLightPosition()
if (pos.x === 0 && pos.y === 0) {
// No custom position.
}
// Replace with
const ret = win.getWindowButtonPosition()
if (ret === null) {
// No custom position.
}
已移除: ipcRenderer.sendTo()
ipcRenderer.sendTo() API 已被移除。应使用在渲染器之间设置 MessageChannel 来代替。
IpcRendererEvent 的 senderId 和 senderIsMainFrame 属性也已被移除。
移除:app.runningUnderRosettaTranslation
app.runningUnderRosettaTranslation 属性已被移除。 请改用 app.runningUnderARM64Translation。
// Removed
console.log(app.runningUnderRosettaTranslation)
// Replace with
console.log(app.runningUnderARM64Translation)
已弃用:app 上的 renderer-process-crashed 事件
app 上的 renderer-process-crashed 事件已被弃用。请改用新的 render-process-gone 事件。
// Deprecated
app.on('renderer-process-crashed', (event, webContents, killed) => { /* ... */ })
// Replace with
app.on('render-process-gone', (event, webContents, details) => { /* ... */ })
已弃用:WebContents 上 context-menu 事件的 params.inputFormType 属性
WebContents 上的 context-menu 事件的 params 对象中的 inputFormType 属性已被弃用。请改用新的 formControlType 属性。
已弃用:WebContents 和 <webview> 上的 crashed 事件
WebContents 和 <webview> 上的 crashed 事件已被弃用。请改用新的 render-process-gone 事件。
// Deprecated
win.webContents.on('crashed', (event, killed) => { /* ... */ })
webview.addEventListener('crashed', (event) => { /* ... */ })
// Replace with
win.webContents.on('render-process-gone', (event, details) => { /* ... */ })
webview.addEventListener('render-process-gone', (event) => { /* ... */ })
已弃用:app 上的 gpu-process-crashed 事件
app 上的 gpu-process-crashed 事件已被弃用。请改用新的 child-process-gone 事件。
// Deprecated
app.on('gpu-process-crashed', (event, killed) => { /* ... */ })
// Replace with
app.on('child-process-gone', (event, details) => { /* ... */ })
计划中的重大 API 变更 (27.0)
已移除:对 macOS 10.13 / 10.14 的支持
Chromium 不再支持 macOS 10.13 (High Sierra) 和 macOS 10.14 (Mojave)。
旧版本的 Electron 将继续在这些操作系统上运行,但运行 Electron v27.0.0 及更高版本将需要 macOS 10.15 (Catalina) 或更高版本。
已弃用:ipcRenderer.sendTo()
ipcRenderer.sendTo() API 已被弃用。应使用在渲染器之间设置 MessageChannel 来代替。
IpcRendererEvent 的 senderId 和 senderIsMainFrame 属性也已被弃用。
已移除:systemPreferences 中的配色方案事件
以下 systemPreferences 事件已被移除:
inverted-color-scheme-changedhigh-contrast-color-scheme-changed
请改用 nativeTheme 模块上新的 updated 事件。
// Removed
systemPreferences.on('inverted-color-scheme-changed', () => { /* ... */ })
systemPreferences.on('high-contrast-color-scheme-changed', () => { /* ... */ })
// Replace with
nativeTheme.on('updated', () => { /* ... */ })
已移除:macOS 上 window.setVibrancy 的部分选项
以下 vibrancy 选项已被移除
- 'light'
- 'medium-light'
- 'dark'
- 'ultra-dark'
- 'appearance-based'
这些选项此前已被弃用,并且已被 Apple 在 10.15 版本中移除。
已移除:webContents.getPrinters
webContents.getPrinters 方法已被移除。 请改用 webContents.getPrintersAsync。
const w = new BrowserWindow({ show: false })
// Removed
console.log(w.webContents.getPrinters())
// Replace with
w.webContents.getPrintersAsync().then((printers) => {
console.log(printers)
})
已移除:systemPreferences.{get,set}AppLevelAppearance 和 systemPreferences.appLevelAppearance
systemPreferences.getAppLevelAppearance 和 systemPreferences.setAppLevelAppearance 方法以及 systemPreferences.appLevelAppearance 属性已移除。 请改用 nativeTheme 模块。
// Removed
systemPreferences.getAppLevelAppearance()
// Replace with
nativeTheme.shouldUseDarkColors
// Removed
systemPreferences.appLevelAppearance
// Replace with
nativeTheme.shouldUseDarkColors
// Removed
systemPreferences.setAppLevelAppearance('dark')
// Replace with
nativeTheme.themeSource = 'dark'
已移除:systemPreferences.getColor 的 alternate-selected-control-text 值
systemPreferences.getColor 的 alternate-selected-control-text 值已被移除。 请改用 selected-content-background。
// Removed
systemPreferences.getColor('alternate-selected-control-text')
// Replace with
systemPreferences.getColor('selected-content-background')
计划中的重大 API 变更 (26.0)
已废弃:webContents.getPrinters
webContents.getPrinters 方法已被废弃。 请改用 webContents.getPrintersAsync。
const w = new BrowserWindow({ show: false })
// Deprecated
console.log(w.webContents.getPrinters())
// Replace with
w.webContents.getPrintersAsync().then((printers) => {
console.log(printers)
})
已弃用:systemPreferences.{get,set}AppLevelAppearance 和 systemPreferences.appLevelAppearance
systemPreferences.getAppLevelAppearance 和 systemPreferences.setAppLevelAppearance 方法以及 systemPreferences.appLevelAppearance 属性已被弃用。请改用 nativeTheme 模块。
// Deprecated
systemPreferences.getAppLevelAppearance()
// Replace with
nativeTheme.shouldUseDarkColors
// Deprecated
systemPreferences.appLevelAppearance
// Replace with
nativeTheme.shouldUseDarkColors
// Deprecated
systemPreferences.setAppLevelAppearance('dark')
// Replace with
nativeTheme.themeSource = 'dark'
已弃用:systemPreferences.getColor 的 alternate-selected-control-text 值
systemPreferences.getColor 的 alternate-selected-control-text 值已被废弃。 请改用 selected-content-background。
// Deprecated
systemPreferences.getColor('alternate-selected-control-text')
// Replace with
systemPreferences.getColor('selected-content-background')
计划中的重大 API 变更 (25.0)
已弃用:protocol.{un,}{register,intercept}{Buffer,String,Stream,File,Http}Protocol 和 protocol.isProtocol{Registered,Intercepted}
protocol.register*Protocol 和 protocol.intercept*Protocol 方法已被 protocol.handle 取代。
新方法既可以注册一个新协议,也可以拦截一个现有协议,并且响应可以是任何类型。
// Deprecated in Electron 25
protocol.registerBufferProtocol('some-protocol', () => {
callback({ mimeType: 'text/html', data: Buffer.from('<h5>Response</h5>') })
})
// Replace with
protocol.handle('some-protocol', () => {
return new Response(
Buffer.from('<h5>Response</h5>'), // Could also be a string or ReadableStream.
{ headers: { 'content-type': 'text/html' } }
)
})
// Deprecated in Electron 25
protocol.registerHttpProtocol('some-protocol', () => {
callback({ url: 'https://electron.js.cn' })
})
// Replace with
protocol.handle('some-protocol', () => {
return net.fetch('https://electron.js.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)
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()
BrowserWindow.getTrafficLightPosition() 已被弃用,应改用 BrowserWindow.getWindowButtonPosition() API,该 API 在没有自定义位置时返回 null 而非 { x: 0, y: 0 }。
// Deprecated in Electron 25
const pos = win.getTrafficLightPosition()
if (pos.x === 0 && pos.y === 0) {
// No custom position.
}
// Replace with
const ret = win.getWindowButtonPosition()
if (ret === null) {
// No custom position.
}
计划中的重大 API 变更 (24.0)
API 变更:nativeImage.createThumbnailFromPath(path, size)
maxSize 参数已更改为 size,以反映传入的大小将是创建的缩略图的大小。以前,如果图像小于 maxSize,Windows 不会放大图像,而 macOS 总是将大小设置为 maxSize。现在,跨平台的行为相同。
更新的行为
// a 128x128 image.
const imagePath = path.join('path', 'to', 'capybara.png')
// Scaling up a smaller image.
const upSize = { width: 256, height: 256 }
nativeImage.createThumbnailFromPath(imagePath, upSize).then(result => {
console.log(result.getSize()) // { width: 256, height: 256 }
})
// Scaling down a larger image.
const downSize = { width: 64, height: 64 }
nativeImage.createThumbnailFromPath(imagePath, downSize).then(result => {
console.log(result.getSize()) // { width: 64, height: 64 }
})
先前行为(在 Windows 上)
// a 128x128 image
const imagePath = path.join('path', 'to', 'capybara.png')
const size = { width: 256, height: 256 }
nativeImage.createThumbnailFromPath(imagePath, size).then(result => {
console.log(result.getSize()) // { width: 128, height: 128 }
})
计划中的重大 API 变更 (23.0)
行为已更改:macOS 上的可拖动区域
macOS 上可拖动区域(使用 CSS 属性 -webkit-app-region: drag)的实现已更改,以使其与 Windows 和 Linux 一致。以前,当一个具有 -webkit-app-region: no-drag 的区域与一个具有 -webkit-app-region: drag 的区域重叠时,在 macOS 上 no-drag 区域总是优先,而忽略 CSS 层叠。也就是说,如果一个 drag 区域位于 no-drag 区域之上,它将被忽略。自 Electron 23 起,位于 no-drag 区域上方的 drag 区域将正确地使其成为可拖动区域。
此外,customButtonsOnHover BrowserWindow 属性以前会创建一个可拖动区域,该区域会忽略 -webkit-app-region CSS 属性。这现在已修复(有关讨论,请参阅 #37210)。
因此,如果您的应用程序在 macOS 上使用无边框窗口和可拖动区域,则在 Electron 23 中,您应用程序中可拖动的区域可能会发生变化。
已移除:Windows 7 / 8 / 8.1 支持
Windows 7、Windows 8 和 Windows 8.1 不再受支持。Electron 遵循 Chromium 的计划弃用策略,该策略将在 Chromium 109 早期弃用 Windows 7 支持。
旧版本的 Electron 将继续在这些操作系统上运行,但运行 Electron v23.0.0 及更高版本需要 Windows 10 或更高版本。
已移除:BrowserWindow scroll-touch-* 事件
BrowserWindow 上已弃用的 scroll-touch-begin、scroll-touch-end 和 scroll-touch-edge 事件已被移除。请改用 WebContents 上新提供的 input-event 事件。
// Removed in Electron 23.0
win.on('scroll-touch-begin', scrollTouchBegin)
win.on('scroll-touch-edge', scrollTouchEdge)
win.on('scroll-touch-end', scrollTouchEnd)
// Replace with
win.webContents.on('input-event', (_, event) => {
if (event.type === 'gestureScrollBegin') {
scrollTouchBegin()
} else if (event.type === 'gestureScrollUpdate') {
scrollTouchEdge()
} else if (event.type === 'gestureScrollEnd') {
scrollTouchEnd()
}
})
已移除:webContents.incrementCapturerCount(stayHidden, stayAwake)
webContents.incrementCapturerCount(stayHidden, stayAwake) 函数已被移除。现在,当页面捕获完成时,它由 webContents.capturePage 自动处理。
const w = new BrowserWindow({ show: false })
// Removed in Electron 23
w.webContents.incrementCapturerCount()
w.capturePage().then(image => {
console.log(image.toDataURL())
w.webContents.decrementCapturerCount()
})
// Replace with
w.capturePage().then(image => {
console.log(image.toDataURL())
})
已移除:webContents.decrementCapturerCount(stayHidden, stayAwake)
webContents.decrementCapturerCount(stayHidden, stayAwake) 函数已被移除。现在,当页面捕获完成时,它由 webContents.capturePage 自动处理。
const w = new BrowserWindow({ show: false })
// Removed in Electron 23
w.webContents.incrementCapturerCount()
w.capturePage().then(image => {
console.log(image.toDataURL())
w.webContents.decrementCapturerCount()
})
// Replace with
w.capturePage().then(image => {
console.log(image.toDataURL())
})
计划中的重大 API 变更 (22.0)
已弃用:webContents.incrementCapturerCount(stayHidden, stayAwake)
webContents.incrementCapturerCount(stayHidden, stayAwake) 已被弃用。 现在当页面捕获完成时,它由 webContents.capturePage 自动处理。
const w = new BrowserWindow({ show: false })
// Removed in Electron 23
w.webContents.incrementCapturerCount()
w.capturePage().then(image => {
console.log(image.toDataURL())
w.webContents.decrementCapturerCount()
})
// Replace with
w.capturePage().then(image => {
console.log(image.toDataURL())
})
已弃用:webContents.decrementCapturerCount(stayHidden, stayAwake)
webContents.decrementCapturerCount(stayHidden, stayAwake) 已被弃用。 现在当页面捕获完成时,它由 webContents.capturePage 自动处理。
const w = new BrowserWindow({ show: false })
// Removed in Electron 23
w.webContents.incrementCapturerCount()
w.capturePage().then(image => {
console.log(image.toDataURL())
w.webContents.decrementCapturerCount()
})
// Replace with
w.capturePage().then(image => {
console.log(image.toDataURL())
})
已移除: WebContents 的 new-window 事件
WebContents 的 new-window 事件已被移除。它被 webContents.setWindowOpenHandler() 取代。
// Removed in Electron 22
webContents.on('new-window', (event) => {
event.preventDefault()
})
// Replace with
webContents.setWindowOpenHandler((details) => {
return { action: 'deny' }
})
已移除:<webview> new-window 事件
<webview> 的 new-window 事件已被移除。没有直接的替代方案。
// Removed in Electron 22
webview.addEventListener('new-window', (event) => {})
// Replace with
// main.js
mainWindow.webContents.on('did-attach-webview', (event, wc) => {
wc.setWindowOpenHandler((details) => {
mainWindow.webContents.send('webview-new-window', wc.id, details)
return { action: 'deny' }
})
})
// preload.js
const { ipcRenderer } = require('electron')
ipcRenderer.on('webview-new-window', (e, webContentsId, details) => {
console.log('webview-new-window', webContentsId, details)
document.getElementById('webview').dispatchEvent(new Event('new-window'))
})
// renderer.js
document.getElementById('webview').addEventListener('new-window', () => {
console.log('got new-window event')
})
已弃用:BrowserWindow scroll-touch-* 事件
BrowserWindow 上的 scroll-touch-begin、scroll-touch-end 和 scroll-touch-edge 事件已被弃用。请改用 WebContents 上新提供的 input-event 事件。
// Deprecated
win.on('scroll-touch-begin', scrollTouchBegin)
win.on('scroll-touch-edge', scrollTouchEdge)
win.on('scroll-touch-end', scrollTouchEnd)
// Replace with
win.webContents.on('input-event', (_, event) => {
if (event.type === 'gestureScrollBegin') {
scrollTouchBegin()
} else if (event.type === 'gestureScrollUpdate') {
scrollTouchEdge()
} else if (event.type === 'gestureScrollEnd') {
scrollTouchEnd()
}
})
计划中的重大 API 变更 (21.0)
行为已更改:已启用 V8 内存笼
V8 内存笼已被启用,这对包装非 V8 内存的 ArrayBuffer 或 Buffer 的原生模块有影响。有关更多详细信息,请参阅 关于 V8 内存笼的博文。
API 已更改:webContents.printToPDF()
webContents.printToPDF() 已进行修改,以符合 Chrome DevTools Protocol 中的 Page.printToPDF。这是为了解决上游的更改,这些更改使得我们之前的实现不可行且充满错误。
参数已更改
pageRanges
参数已移除
printSelectionOnlymarginsTypeheaderFooterscaleFactor
参数已添加
headerTemplatefooterTemplatedisplayHeaderFootermarginsscalepreferCSSPageSize
// Main process
const { webContents } = require('electron')
webContents.printToPDF({
landscape: true,
displayHeaderFooter: true,
printBackground: true,
scale: 2,
pageSize: 'Ledger',
margins: {
top: 2,
bottom: 2,
left: 2,
right: 2
},
pageRanges: '1-5, 8, 11-13',
headerTemplate: '<h1>Title</h1>',
footerTemplate: '<div><span class="pageNumber"></span></div>',
preferCSSPageSize: true
}).then(data => {
fs.writeFile(pdfPath, data, (error) => {
if (error) throw error
console.log(`Wrote PDF successfully to ${pdfPath}`)
})
}).catch(error => {
console.log(`Failed to write PDF to ${pdfPath}: `, error)
})
计划中的重大 API 变更 (20.0)
已移除:macOS 10.11 / 10.12 支持
Chromium 不再支持 macOS 10.11 (El Capitan) 和 macOS 10.12 (Sierra)。
旧版本的 Electron 将继续在这些操作系统上运行,但运行 Electron v20.0.0 及更高版本需要 macOS 10.13 (High Sierra) 或更高版本。
默认更改:没有 nodeIntegration: true 的渲染器默认已沙盒化
以前,指定了预加载脚本的渲染器默认未沙盒化。这意味着默认情况下,预加载脚本可以访问 Node.js。在 Electron 20 中,此默认设置已更改。从 Electron 20 开始,除非指定了 nodeIntegration: true 或 sandbox: false,否则渲染器默认将已沙盒化。
如果您的预加载脚本不依赖 Node,则无需执行任何操作。如果您的预加载脚本确实依赖 Node,请重构它们以从渲染器中移除 Node 使用,或为相关的渲染器显式指定 sandbox: false。
已移除:Linux 上的 skipTaskbar
在 X11 上,skipTaskbar 会向 X11 窗口管理器发送一个 _NET_WM_STATE_SKIP_TASKBAR 消息。Wayland 没有直接的等效项,并且已知的解决方法存在不可接受的权衡(例如,GNOME 中的 Window.is_skip_taskbar 需要不安全模式),因此 Electron 无法在 Linux 上支持此功能。
API 已更改:session.setDevicePermissionHandler(handler)
使用 session.setDevicePermissionHandler(handler) 时调用的处理程序的参数已发生更改。此处理程序不再接收 frame WebFrameMain,而是接收 origin,即正在检查设备权限的来源。
计划中的重大 API 变更 (19.0)
已移除:IA32 Linux 二进制文件
这是由于 Chromium 102.0.4999.0 放弃了对 IA32 Linux 的支持。这标志着 IA32 Linux 支持的移除。
计划中的重大 API 变更 (18.0)
已移除:nativeWindowOpen
在 Electron 15 之前,window.open 默认会通过 BrowserWindowProxy 进行包装。这意味着 window.open('about:blank') 无法打开同步脚本可写的子窗口,以及其他不兼容问题。自 Electron 15 起,nativeWindowOpen 已默认启用。
有关更多详细信息,请参阅 Electron 中 window.open 的文档。
计划中的重大 API 变更 (17.0)
已移除:渲染器中的 desktopCapturer.getSources
desktopCapturer.getSources API 现在仅在主进程中可用。此更改旨在提高 Electron 应用程序的默认安全性。
如果需要此功能,可以按以下方式替换
// Main process
const { ipcMain, desktopCapturer } = require('electron')
ipcMain.handle(
'DESKTOP_CAPTURER_GET_SOURCES',
(event, opts) => desktopCapturer.getSources(opts)
)
// Renderer process
const { ipcRenderer } = require('electron')
const desktopCapturer = {
getSources: (opts) => ipcRenderer.invoke('DESKTOP_CAPTURER_GET_SOURCES', opts)
}
但是,您应该考虑进一步限制返回给渲染器的信息;例如,向用户显示一个源选择器,并且只返回选定的源。
已弃用:nativeWindowOpen
在 Electron 15 之前,window.open 默认会通过 BrowserWindowProxy 进行包装。这意味着 window.open('about:blank') 无法打开同步脚本可写的子窗口,以及其他不兼容问题。自 Electron 15 起,nativeWindowOpen 已默认启用。
有关更多详细信息,请参阅 Electron 中 window.open 的文档。
计划中的重大 API 变更 (16.0)
行为已更改:Linux 上 crashReporter 实现已切换到 Crashpad
Linux 上 crashReporter API 的底层实现已从 Breakpad 切换到 Crashpad,使其与 Windows 和 Mac 一致。因此,子进程现在会自动被监视,并且不再需要在 Node 子进程中调用 process.crashReporter.start(也不建议这样做,因为它会启动第二个 Crashpad 报告器实例)。
在 Linux 上,注释的报告方式也发生了一些细微变化,包括长值将不再被拆分到以 __1、__2 等结尾的注释之间,而是会被截断到(新的、更长的)注释值限制。
已弃用:渲染器中的 desktopCapturer.getSources
在渲染器中使用 desktopCapturer.getSources API 已被弃用,并将在未来移除。此更改提高了 Electron 应用程序的默认安全性。
有关如何替换应用程序中此 API 的详细信息,请参阅 此处。
计划中的重大 API 变更 (15.0)
默认更改:nativeWindowOpen 默认为 true
在 Electron 15 之前,window.open 默认会通过 BrowserWindowProxy 进行包装。这意味着 window.open('about:blank') 无法打开同步脚本可写的子窗口,以及其他不兼容问题。nativeWindowOpen 不再是实验性的,现在是默认选项。
有关更多详细信息,请参阅 Electron 中 window.open 的文档。
已弃用:app.runningUnderRosettaTranslation
app.runningUnderRosettaTranslation 属性已被弃用。请改用 app.runningUnderARM64Translation。
// Deprecated
console.log(app.runningUnderRosettaTranslation)
// Replace with
console.log(app.runningUnderARM64Translation)
计划中的重大 API 变更 (14.0)
已移除:remote 模块
remote 模块在 Electron 12 中被弃用,将在 Electron 14 中移除。它被 @electron/remote 模块取代。
// Deprecated in Electron 12:
const { BrowserWindow } = require('electron').remote
// Replace with:
const { BrowserWindow } = require('@electron/remote')
// In the main process:
require('@electron/remote/main').initialize()
已移除:app.allowRendererProcessReuse
app.allowRendererProcessReuse 属性将被移除,这是我们为了更紧密地与 Chromium 的进程模型对齐,以提高安全性、性能和可维护性的一部分。
有关更多详细信息,请参阅 #18397。
已移除:BrowserWindow 亲和性
在构造新的 BrowserWindow 时,affinity 选项将被移除,这是我们为了更紧密地与 Chromium 的进程模型对齐,以提高安全性、性能和可维护性的一部分。
有关更多详细信息,请参阅 #18397。
API 已更改:window.open()
可选参数 frameName 将不再设置窗口的标题。现在这遵循 原生文档 中对应参数 windowName 的规范。
如果您曾使用此参数设置窗口标题,现在可以使用 win.setTitle(title) 来代替。
已移除:worldSafeExecuteJavaScript
在 Electron 14 中,worldSafeExecuteJavaScript 将被移除。没有替代方案,请确保您的代码在使用此属性启用后能够正常工作。自 Electron 12 起,它已默认启用。
如果您使用 webFrame.executeJavaScript 或 webFrame.executeJavaScriptInIsolatedWorld,将受到此更改的影响。您需要确保通过这些方法返回的值受 Context Bridge API 支持,因为这些方法使用相同的传值语义。
已移除:BrowserWindowConstructorOptions 从父窗口继承
在 Electron 14 之前,使用 window.open 打开的窗口会继承其父窗口的 BrowserWindow 构造函数选项,例如 transparent 和 resizable。从 Electron 14 开始,此行为已被移除,窗口将不会继承其父窗口的任何 BrowserWindow 构造函数选项。
取而代之的是,使用 setWindowOpenHandler 为新窗口显式设置选项。
webContents.setWindowOpenHandler((details) => {
return {
action: 'allow',
overrideBrowserWindowOptions: {
// ...
}
}
})
已移除:additionalFeatures
WebContents 的 new-window 和 did-create-window 事件中已弃用的 additionalFeatures 属性已被移除。由于 new-window 使用位置参数,该参数仍然存在,但将始终为空数组 []。(尽管请注意,new-window 事件本身已被弃用,并被 setWindowOpenHandler 取代。)窗口特性中的裸键现在会作为键,值为 true 出现在选项对象中。
// Removed in Electron 14
// Triggered by window.open('...', '', 'my-key')
webContents.on('did-create-window', (window, details) => {
if (details.additionalFeatures.includes('my-key')) {
// ...
}
})
// Replace with
webContents.on('did-create-window', (window, details) => {
if (details.options['my-key']) {
// ...
}
})
计划中的重大 API 变更 (13.0)
API 已更改:session.setPermissionCheckHandler(handler)
handler 方法的第一个参数以前始终是 webContents,现在有时会是 null。您应该使用 requestingOrigin、embeddingOrigin 和 securityOrigin 属性来正确响应权限检查。由于 webContents 可能为 null,因此不能再依赖它。
// Old code
session.setPermissionCheckHandler((webContents, permission) => {
if (webContents.getURL().startsWith('https://google.com/') && permission === 'notification') {
return true
}
return false
})
// Replace with
session.setPermissionCheckHandler((webContents, permission, requestingOrigin) => {
if (new URL(requestingOrigin).hostname === 'google.com' && permission === 'notification') {
return true
}
return false
})
已移除:shell.moveItemToTrash()
已弃用的同步 shell.moveItemToTrash() API 已被移除。请改用异步 shell.trashItem()。
// Removed in Electron 13
shell.moveItemToTrash(path)
// Replace with
shell.trashItem(path).then(/* ... */)
已移除:BrowserWindow 扩展 API
已弃用的扩展 API 已被移除
BrowserWindow.addExtension(path)BrowserWindow.addDevToolsExtension(path)BrowserWindow.removeExtension(name)BrowserWindow.removeDevToolsExtension(name)BrowserWindow.getExtensions()BrowserWindow.getDevToolsExtensions()
请改用 session API
ses.loadExtension(path)ses.removeExtension(extension_id)ses.getAllExtensions()
// Removed in Electron 13
BrowserWindow.addExtension(path)
BrowserWindow.addDevToolsExtension(path)
// Replace with
session.defaultSession.loadExtension(path)
// Removed in Electron 13
BrowserWindow.removeExtension(name)
BrowserWindow.removeDevToolsExtension(name)
// Replace with
session.defaultSession.removeExtension(extension_id)
// Removed in Electron 13
BrowserWindow.getExtensions()
BrowserWindow.getDevToolsExtensions()
// Replace with
session.defaultSession.getAllExtensions()
已移除:systemPreferences 中的方法
以下 systemPreferences 方法已被弃用
systemPreferences.isDarkMode()systemPreferences.isInvertedColorScheme()systemPreferences.isHighContrastColorScheme()
请改用以下 nativeTheme 属性
nativeTheme.shouldUseDarkColorsnativeTheme.shouldUseInvertedColorSchemenativeTheme.shouldUseHighContrastColors
// Removed in Electron 13
systemPreferences.isDarkMode()
// Replace with
nativeTheme.shouldUseDarkColors
// Removed in Electron 13
systemPreferences.isInvertedColorScheme()
// Replace with
nativeTheme.shouldUseInvertedColorScheme
// Removed in Electron 13
systemPreferences.isHighContrastColorScheme()
// Replace with
nativeTheme.shouldUseHighContrastColors
已弃用:WebContents new-window 事件
WebContents 的 new-window 事件已被弃用。它被 webContents.setWindowOpenHandler() 取代。
// Deprecated in Electron 13
webContents.on('new-window', (event) => {
event.preventDefault()
})
// Replace with
webContents.setWindowOpenHandler((details) => {
return { action: 'deny' }
})
计划中的重大 API 变更 (12.0)
已移除:Pepper Flash 支持
Chromium 已移除 Flash 支持,我们也不得不跟进。有关更多详细信息,请参阅 Chromium 的 Flash Roadmap。
默认值已更改:worldSafeExecuteJavaScript 默认为 true
在 Electron 12 中,worldSafeExecuteJavaScript 将默认启用。要恢复以前的行为,必须在 WebPreferences 中指定 worldSafeExecuteJavaScript: false。请注意,将此选项设置为 false 是不安全的。
此选项将在 Electron 14 中移除,因此请迁移您的代码以支持默认值。
默认值已更改:contextIsolation 默认为 true
在 Electron 12 中,contextIsolation 将默认启用。要恢复以前的行为,必须在 WebPreferences 中指定 contextIsolation: false。
我们建议启用 contextIsolation 以确保您应用程序的安全性。
另一个影响是,除非 nodeIntegration 为 true 且 contextIsolation 为 false,否则不能在渲染器进程中使用 require()。
有关更多详细信息,请参阅:https://github.com/electron/electron/issues/23506
已移除:crashReporter.getCrashesDirectory()
crashReporter.getCrashesDirectory 方法已被移除。使用应替换为 app.getPath('crashDumps')。
// Removed in Electron 12
crashReporter.getCrashesDirectory()
// Replace with
app.getPath('crashDumps')
已移除:渲染器进程中的 crashReporter 方法
以下 crashReporter 方法在渲染器进程中不再可用
crashReporter.startcrashReporter.getLastCrashReportcrashReporter.getUploadedReportscrashReporter.getUploadToServercrashReporter.setUploadToServercrashReporter.getCrashesDirectory
它们只能从主进程调用。
有关更多详细信息,请参阅 #23265。
默认值已更改:crashReporter.start({ compress: true })
crashReporter.start 的 compress 选项的默认值已从 false 更改为 true。这意味着崩溃转储将使用 Content-Encoding: gzip 标头上传到崩溃收集服务器,并且正文将被压缩。
如果您的崩溃收集服务器不支持压缩负载,则可以通过在 crash reporter 选项中指定 { compress: false } 来禁用压缩。
已弃用:remote 模块
remote 模块在 Electron 12 中被弃用,将在 Electron 14 中移除。它被 @electron/remote 模块取代。
// Deprecated in Electron 12:
const { BrowserWindow } = require('electron').remote
// Replace with:
const { BrowserWindow } = require('@electron/remote')
// In the main process:
require('@electron/remote/main').initialize()
已弃用:shell.moveItemToTrash()
同步的 shell.moveItemToTrash() 已被新的异步 shell.trashItem() 取代。
// Deprecated in Electron 12
shell.moveItemToTrash(path)
// Replace with
shell.trashItem(path).then(/* ... */)
计划中的重大 API 变更 (11.0)
已移除:BrowserView.{destroy, fromId, fromWebContents, getAllViews} 和 BrowserView 的 id 属性
实验性 API BrowserView.{destroy, fromId, fromWebContents, getAllViews} 已被移除。此外,BrowserView 的 id 属性也已被移除。
有关更详细的信息,请参阅 #23578。
计划中的重大 API 变更 (10.0)
已弃用:crashReporter.start() 的 companyName 参数
crashReporter.start() 的 companyName 参数以前是必需的,现在是可选的,并且已被弃用。要以非弃用方式获得相同行为,可以在 globalExtra 中传递 companyName 值。
// Deprecated in Electron 10
crashReporter.start({ companyName: 'Umbrella Corporation' })
// Replace with
crashReporter.start({ globalExtra: { _companyName: 'Umbrella Corporation' } })
已弃用:crashReporter.getCrashesDirectory()
crashReporter.getCrashesDirectory 方法已被弃用。使用应替换为 app.getPath('crashDumps')。
// Deprecated in Electron 10
crashReporter.getCrashesDirectory()
// Replace with
app.getPath('crashDumps')
已弃用:渲染器进程中的 crashReporter 方法
从渲染器进程调用以下 crashReporter 方法是已弃用的
crashReporter.startcrashReporter.getLastCrashReportcrashReporter.getUploadedReportscrashReporter.getUploadToServercrashReporter.setUploadToServercrashReporter.getCrashesDirectory
在渲染器中 crashReporter 模块中剩余的非弃用方法是 addExtraParameter、removeExtraParameter 和 getParameters。
当从主进程调用时,以上所有方法仍然是非弃用的。
有关更多详细信息,请参阅 #23265。
已弃用:crashReporter.start({ compress: false })
设置 crashReporter.start 中的 { compress: false } 已被弃用。几乎所有的崩溃收集服务器都支持 gzip 压缩。此选项将在未来的 Electron 版本中移除。
默认值已更改:enableRemoteModule 默认为 false
在 Electron 9 中,在 WebPreferences 的 enableRemoteModule 选项中未显式启用 remote 模块就开始发出警告。在 Electron 10 中,remote 模块现在默认禁用。要使用 remote 模块,必须在 WebPreferences 中指定 enableRemoteModule: true。
const w = new BrowserWindow({
webPreferences: {
enableRemoteModule: true
}
})
protocol.unregisterProtocol
protocol.uninterceptProtocol
这些 API 现在是同步的,并且不再需要可选的回调。
// Deprecated
protocol.unregisterProtocol(scheme, () => { /* ... */ })
// Replace with
protocol.unregisterProtocol(scheme)
protocol.registerFileProtocol
protocol.registerBufferProtocol
protocol.registerStringProtocol
protocol.registerHttpProtocol
protocol.registerStreamProtocol
protocol.interceptFileProtocol
protocol.interceptStringProtocol
protocol.interceptBufferProtocol
protocol.interceptHttpProtocol
protocol.interceptStreamProtocol
这些 API 现在是同步的,并且不再需要可选的回调。
// Deprecated
protocol.registerFileProtocol(scheme, handler, () => { /* ... */ })
// Replace with
protocol.registerFileProtocol(scheme, handler)
注册或拦截的协议在导航发生之前对当前页面无效。
protocol.isProtocolHandled
此 API 已弃用,用户应使用 protocol.isProtocolRegistered 和 protocol.isProtocolIntercepted 来代替。
// Deprecated
protocol.isProtocolHandled(scheme).then(() => { /* ... */ })
// Replace with
const isRegistered = protocol.isProtocolRegistered(scheme)
const isIntercepted = protocol.isProtocolIntercepted(scheme)
计划中的重大 API 变更 (9.0)
默认值已更改:在渲染器进程中加载非上下文感知原生模块默认禁用
从 Electron 9 开始,我们不允许在渲染器进程中加载非上下文感知原生模块。这是为了提高 Electron 作为项目的安全性、性能和可维护性。
如果这影响到您,您可以暂时将 app.allowRendererProcessReuse 设置为 false 来恢复旧的行为。此标志将仅在 Electron 11 之前可用,因此您应该计划更新您的原生模块以使其具有上下文感知能力。
有关更多详细信息,请参阅 #18397。
已弃用:BrowserWindow 扩展 API
以下扩展 API 已被弃用
BrowserWindow.addExtension(path)BrowserWindow.addDevToolsExtension(path)BrowserWindow.removeExtension(name)BrowserWindow.removeDevToolsExtension(name)BrowserWindow.getExtensions()BrowserWindow.getDevToolsExtensions()
请改用 session API
ses.loadExtension(path)ses.removeExtension(extension_id)ses.getAllExtensions()
// Deprecated in Electron 9
BrowserWindow.addExtension(path)
BrowserWindow.addDevToolsExtension(path)
// Replace with
session.defaultSession.loadExtension(path)
// Deprecated in Electron 9
BrowserWindow.removeExtension(name)
BrowserWindow.removeDevToolsExtension(name)
// Replace with
session.defaultSession.removeExtension(extension_id)
// Deprecated in Electron 9
BrowserWindow.getExtensions()
BrowserWindow.getDevToolsExtensions()
// Replace with
session.defaultSession.getAllExtensions()
已移除:<webview>.getWebContents()
此 API 在 Electron 8.0 中已被弃用,现在已移除。
// Removed in Electron 9.0
webview.getWebContents()
// Replace with
const { remote } = require('electron')
remote.webContents.fromId(webview.getWebContentsId())
已移除:webFrame.setLayoutZoomLevelLimits()
Chromium 已移除更改布局缩放级别限制的支持,Electron 无法维护。该函数在 Electron 8.x 中已被弃用,并在 Electron 9.x 中被移除。布局缩放级别限制现在固定为最低 0.25 和最高 5.0,如 此处 定义。
行为已更改:通过 IPC 发送非 JS 对象现在会抛出异常
在 Electron 8.0 中,IPC 已更改为使用结构化克隆算法,带来了显著的性能提升。为了帮助平稳过渡,旧的 IPC 序列化算法被保留并用于一些无法用结构化克隆序列化的对象。特别是,DOM 对象(例如 Element、Location 和 DOMMatrix)、由 C++ 类支持的 Node.js 对象(例如 process.env、Stream 的某些成员)以及由 C++ 类支持的 Electron 对象(例如 WebContents、BrowserWindow 和 WebFrame)无法用结构化克隆序列化。每当调用旧算法时,都会打印弃用警告。
在 Electron 9.0 中,旧的序列化算法已被移除,发送此类不可序列化对象现在将抛出“对象无法克隆”错误。
API 已更改:shell.openItem 现在是 shell.openPath
shell.openItem API 已被一个异步 shell.openPath API 取代。您可以在 此处 查看原始 API 提案和理由。
计划中的重大 API 变更 (8.0)
行为已更改:通过 IPC 发送的值现在使用结构化克隆算法进行序列化
用于序列化通过 IPC 发送的对象(通过 ipcRenderer.send、ipcRenderer.sendSync、WebContents.send 及相关方法)的算法已从自定义算法切换到 V8 内置的 结构化克隆算法,与用于 postMessage 消息序列化的算法相同。这带来了 2 倍的大消息性能提升,但也带来了一些行为上的重大变更。
- 通过 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.")
NaN、Infinity和-Infinity现在将正确序列化,而不是转换为null。- 包含循环引用的对象现在将正确序列化,而不是转换为
null。 Set、Map、Error和RegExp值将正确序列化,而不是转换为{}。BigInt值将正确序列化,而不是转换为null。- 稀疏数组将按原样序列化,而不是转换为包含
null的密集数组。 Date对象将作为Date对象传输,而不是转换为其 ISO 字符串表示。- 类型化数组(如
Uint8Array、Uint16Array、Uint32Array等)将作为类型化数组传输,而不是转换为 Node.jsBuffer。 - Node.js
Buffer对象将作为Uint8Array传输。您可以通过包装底层ArrayBuffer将Uint8Array转换回 Node.jsBuffer。
Buffer.from(value.buffer, value.byteOffset, value.byteLength)
发送任何非原生 JS 类型的对象,例如 DOM 对象(如 Element、Location、DOMMatrix)、Node.js 对象(如 process.env、Stream)或 Electron 对象(如 WebContents、BrowserWindow、WebFrame)已被弃用。在 Electron 8 中,这些对象将像以前一样序列化并带有 DeprecationWarning 消息,但从 Electron 9 开始,发送此类对象将抛出“无法克隆对象”错误。
已弃用:<webview>.getWebContents()
此 API 是使用 remote 模块实现的,该模块具有性能和安全方面的影响。因此,其使用应该是显式的。
// Deprecated
webview.getWebContents()
// Replace with
const { remote } = require('electron')
remote.webContents.fromId(webview.getWebContentsId())
然而,建议完全避免使用 remote 模块。
// main
const { ipcMain, webContents } = require('electron')
const getGuestForWebContents = (webContentsId, contents) => {
const guest = webContents.fromId(webContentsId)
if (!guest) {
throw new Error(`Invalid webContentsId: ${webContentsId}`)
}
if (guest.hostWebContents !== contents) {
throw new Error('Access denied to webContents')
}
return guest
}
ipcMain.handle('openDevTools', (event, webContentsId) => {
const guest = getGuestForWebContents(webContentsId, event.sender)
guest.openDevTools()
})
// renderer
const { ipcRenderer } = require('electron')
ipcRenderer.invoke('openDevTools', webview.getWebContentsId())
已弃用:webFrame.setLayoutZoomLevelLimits()
Chromium 已移除更改布局缩放级别限制的支持,Electron 无法维护。该函数将在 Electron 8.x 中发出警告,并在 Electron 9.x 中停止存在。布局缩放级别限制现在固定为最低 0.25 和最高 5.0,如 此处 定义。
systemPreferences 中已弃用的事件
以下 systemPreferences 事件已被弃用
inverted-color-scheme-changedhigh-contrast-color-scheme-changed
请改用 nativeTheme 模块上新的 updated 事件。
// Deprecated
systemPreferences.on('inverted-color-scheme-changed', () => { /* ... */ })
systemPreferences.on('high-contrast-color-scheme-changed', () => { /* ... */ })
// Replace with
nativeTheme.on('updated', () => { /* ... */ })
已弃用:systemPreferences 中的方法
以下 systemPreferences 方法已被弃用
systemPreferences.isDarkMode()systemPreferences.isInvertedColorScheme()systemPreferences.isHighContrastColorScheme()
请改用以下 nativeTheme 属性
nativeTheme.shouldUseDarkColorsnativeTheme.shouldUseInvertedColorSchemenativeTheme.shouldUseHighContrastColors
// Deprecated
systemPreferences.isDarkMode()
// Replace with
nativeTheme.shouldUseDarkColors
// Deprecated
systemPreferences.isInvertedColorScheme()
// Replace with
nativeTheme.shouldUseInvertedColorScheme
// Deprecated
systemPreferences.isHighContrastColorScheme()
// Replace with
nativeTheme.shouldUseHighContrastColors
计划中的重大 API 变更 (7.0)
已弃用:Atom.io Node Headers URL
这是在 .npmrc 文件中指定为 disturl 或在构建原生 Node 模块时作为 --dist-url 命令行标志指定的 URL。两者在可预见的未来都将得到支持,但建议您进行切换。
已弃用:https://atom.io/download/electron
替换为:https://electron.js.cn/headers
API 已更改:session.clearAuthCache() 不再接受选项
session.clearAuthCache API 不再接受用于清除内容的选项,而是无条件地清除整个缓存。
// Deprecated
session.clearAuthCache({ type: 'password' })
// Replace with
session.clearAuthCache()
API 已更改:powerMonitor.querySystemIdleState 现在是 powerMonitor.getSystemIdleState
// Removed in Electron 7.0
powerMonitor.querySystemIdleState(threshold, callback)
// Replace with synchronous API
const idleState = powerMonitor.getSystemIdleState(threshold)
API 已更改:powerMonitor.querySystemIdleTime 现在是 powerMonitor.getSystemIdleTime
// Removed in Electron 7.0
powerMonitor.querySystemIdleTime(callback)
// Replace with synchronous API
const idleTime = powerMonitor.getSystemIdleTime()
API 已更改:webFrame.setIsolatedWorldInfo 替换了单独的方法
// Removed in Electron 7.0
webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp)
webFrame.setIsolatedWorldHumanReadableName(worldId, name)
webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin)
// Replace with
webFrame.setIsolatedWorldInfo(
worldId,
{
securityOrigin: 'some_origin',
name: 'human_readable_name',
csp: 'content_security_policy'
})
已移除:getBlinkMemoryInfo 上的 marked 属性
此属性在 Chromium 77 中被移除,因此不再可用。
行为已更改:<input type="file"/> 的 webkitdirectory 属性现在列出目录内容
HTML 文件输入上的 webkitdirectory 属性允许它们选择文件夹。Electron 的先前版本有一个错误的实现,其中输入的 event.target.files 返回一个 FileList,该 FileList 返回一个对应于所选文件夹的 File。
自 Electron 7 起,该 FileList 现在是文件夹中所有文件的列表,类似于 Chrome、Firefox 和 Edge(MDN 文档链接)。
作为示例,考虑一个具有以下结构的文件夹
folder
├── file1
├── file2
└── file3
在 Electron <=6 中,这将返回一个 FileList,其中包含一个 File 对象,用于
path/to/folder
在 Electron 7 中,这现在返回一个 FileList,其中包含一个 File 对象,用于
/path/to/folder/file3
/path/to/folder/file2
/path/to/folder/file1
请注意,webkitdirectory 不再公开所选文件夹的路径。如果您需要所选文件夹的路径而不是文件夹内容,请参阅 dialog.showOpenDialog API(链接)。
API 已更改:已实现 Promise 的 API 的基于回调的版本
Electron 5 和 Electron 6 引入了现有异步 API 的 Promise 版本,并弃用了其旧的基于回调的对应版本。在 Electron 7 中,所有已弃用的基于回调的 API 已被移除。
这些函数现在只返回 Promises
app.getFileIcon()#15742app.dock.show()#16904contentTracing.getCategories()#16583contentTracing.getTraceBufferUsage()#16600contentTracing.startRecording()#16584contentTracing.stopRecording()#16584contents.executeJavaScript()#17312cookies.flushStore()#16464cookies.get()#16464cookies.remove()#16464cookies.set()#16464debugger.sendCommand()#16861dialog.showCertificateTrustDialog()#17181inAppPurchase.getProducts()#17355inAppPurchase.purchaseProduct()#17355netLog.stopLogging()#16862session.clearAuthCache()#17259session.clearCache()#17185session.clearHostResolverCache()#17229session.clearStorageData()#17249session.getBlobData()#17303session.getCacheSize()#17185session.resolveProxy()#17222session.setProxy()#17222shell.openExternal()#16176webContents.loadFile()#15855webContents.loadURL()#15855webContents.hasServiceWorker()#16535webContents.printToPDF()#16795webContents.savePage()#16742webFrame.executeJavaScript()#17312webFrame.executeJavaScriptInIsolatedWorld()#17312webviewTag.executeJavaScript()#17312win.capturePage()#15743
这些函数现在有两种形式:同步和基于 Promise 的异步。
dialog.showMessageBox()/dialog.showMessageBoxSync()#17298dialog.showOpenDialog()/dialog.showOpenDialogSync()#16973dialog.showSaveDialog()/dialog.showSaveDialogSync()#17054
计划中的重大 API 变更 (6.0)
API 已更改:win.setMenu(null) 现在是 win.removeMenu()
// Deprecated
win.setMenu(null)
// Replace with
win.removeMenu()
API 已更改:渲染器进程中的 electron.screen 应通过 remote 访问
// Deprecated
require('electron').screen
// Replace with
require('electron').remote.screen
API 已更改:在沙箱化渲染器中 require() Node 内建模块不再隐式加载 remote 版本
// Deprecated
require('child_process')
// Replace with
require('electron').remote.require('child_process')
// Deprecated
require('fs')
// Replace with
require('electron').remote.require('fs')
// Deprecated
require('os')
// Replace with
require('electron').remote.require('os')
// Deprecated
require('path')
// Replace with
require('electron').remote.require('path')
已弃用:powerMonitor.querySystemIdleState 已由 powerMonitor.getSystemIdleState 取代
// Deprecated
powerMonitor.querySystemIdleState(threshold, callback)
// Replace with synchronous API
const idleState = powerMonitor.getSystemIdleState(threshold)
已弃用:powerMonitor.querySystemIdleTime 已由 powerMonitor.getSystemIdleTime 取代
// Deprecated
powerMonitor.querySystemIdleTime(callback)
// Replace with synchronous API
const idleTime = powerMonitor.getSystemIdleTime()
已弃用:app.enableMixedSandbox() 不再需要
// Deprecated
app.enableMixedSandbox()
混合沙箱模式现在已默认启用。
已弃用:Tray.setHighlightMode
在 macOS Catalina 上,我们之前的 Tray 实现会中断。Apple 的原生替代品不支持更改高亮显示行为。
// Deprecated
tray.setHighlightMode(mode)
// API will be removed in v7.0 without replacement.
计划中的重大 API 变更 (5.0)
默认值已更改:nodeIntegration 和 webviewTag 默认为 false,contextIsolation 默认为 true
以下 webPreferences 选项的默认值已被弃用,取而代之的是以下新默认值。
| 属性 | 已弃用的默认值 | 新默认值 |
|---|---|---|
contextIsolation | false | true |
nodeIntegration | true | false |
webviewTag | nodeIntegration(如果已设置),否则为 true | false |
例如,重新启用 webviewTag
const w = new BrowserWindow({
webPreferences: {
webviewTag: true
}
})
行为已更改:通过 nativeWindowOpen 打开的子窗口中的 nodeIntegration
使用 nativeWindowOpen 选项打开的子窗口将始终禁用 Node.js 集成,除非 nodeIntegrationInSubFrames 为 true。
API 已更改:注册特权方案现在必须在 app ready 之前完成
渲染器进程 API webFrame.registerURLSchemeAsPrivileged 和 webFrame.registerURLSchemeAsBypassingCSP 以及浏览器进程 API protocol.registerStandardSchemes 已被移除。已添加新的 API protocol.registerSchemesAsPrivileged,并应使用它来注册具有所需特权的自定义方案。自定义方案必须在 app ready 之前注册。
已弃用:webFrame.setIsolatedWorld* 已由 webFrame.setIsolatedWorldInfo 取代
// Deprecated
webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp)
webFrame.setIsolatedWorldHumanReadableName(worldId, name)
webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin)
// Replace with
webFrame.setIsolatedWorldInfo(
worldId,
{
securityOrigin: 'some_origin',
name: 'human_readable_name',
csp: 'content_security_policy'
})
API 已更改:webFrame.setSpellCheckProvider 现在接受一个异步回调
spellCheck 回调现在是异步的,并且已移除 autoCorrectWord 参数。
// Deprecated
webFrame.setSpellCheckProvider('en-US', true, {
spellCheck: (text) => {
return !spellchecker.isMisspelled(text)
}
})
// Replace with
webFrame.setSpellCheckProvider('en-US', {
spellCheck: (words, callback) => {
callback(words.filter(text => spellchecker.isMisspelled(text)))
}
})
API 已更改:webContents.getZoomLevel 和 webContents.getZoomFactor 现在是同步的
webContents.getZoomLevel 和 webContents.getZoomFactor 不再接受回调参数,而是直接返回其数值。
// Deprecated
webContents.getZoomLevel((level) => {
console.log(level)
})
// Replace with
const level = webContents.getZoomLevel()
console.log(level)
// Deprecated
webContents.getZoomFactor((factor) => {
console.log(factor)
})
// Replace with
const factor = webContents.getZoomFactor()
console.log(factor)
计划中的重大 API 变更 (4.0)
以下列表包含 Electron 4.0 中进行的重大 API 变更。
app.makeSingleInstance
// Deprecated
app.makeSingleInstance((argv, cwd) => {
/* ... */
})
// Replace with
app.requestSingleInstanceLock()
app.on('second-instance', (event, argv, cwd) => {
/* ... */
})
app.releaseSingleInstance
// Deprecated
app.releaseSingleInstance()
// Replace with
app.releaseSingleInstanceLock()
app.getGPUInfo
app.getGPUInfo('complete')
// Now behaves the same with `basic` on macOS
app.getGPUInfo('basic')
win_delay_load_hook
在为 Windows 构建原生模块时,模块 binding.gyp 中的 win_delay_load_hook 变量必须为 true(这是默认值)。如果缺少此钩子,则原生模块在 Windows 上加载时会失败,并出现类似 Cannot find module 的错误消息。更多信息请参阅 原生模块指南。
已移除:IA32 Linux 支持
Electron 18 将不再支持 32 位 Linux 系统。有关更多信息,请参阅 停止支持 32 位 Linux。
重大 API 更改 (3.0)
下表列出了 Electron 3.0 中的重大 API 更改。
app
// Deprecated
app.getAppMemoryInfo()
// Replace with
app.getAppMetrics()
// Deprecated
const metrics = app.getAppMetrics()
const { memory } = metrics[0] // Deprecated property
BrowserWindow
// Deprecated
const optionsA = { webPreferences: { blinkFeatures: '' } }
const windowA = new BrowserWindow(optionsA)
// Replace with
const optionsB = { webPreferences: { enableBlinkFeatures: '' } }
const windowB = new BrowserWindow(optionsB)
// Deprecated
window.on('app-command', (e, cmd) => {
if (cmd === 'media-play_pause') {
// do something
}
})
// Replace with
window.on('app-command', (e, cmd) => {
if (cmd === 'media-play-pause') {
// do something
}
})
clipboard
// Deprecated
clipboard.readRtf()
// Replace with
clipboard.readRTF()
// Deprecated
clipboard.writeRtf()
// Replace with
clipboard.writeRTF()
// Deprecated
clipboard.readHtml()
// Replace with
clipboard.readHTML()
// Deprecated
clipboard.writeHtml()
// Replace with
clipboard.writeHTML()
crashReporter
// Deprecated
crashReporter.start({
companyName: 'Crashly',
submitURL: 'https://crash.server.com',
autoSubmit: true
})
// Replace with
crashReporter.start({
companyName: 'Crashly',
submitURL: 'https://crash.server.com',
uploadToServer: true
})
nativeImage
// Deprecated
nativeImage.createFromBuffer(buffer, 1.0)
// Replace with
nativeImage.createFromBuffer(buffer, {
scaleFactor: 1.0
})
process
// Deprecated
const info = process.getProcessMemoryInfo()
screen
// Deprecated
screen.getMenuBarHeight()
// Replace with
screen.getPrimaryDisplay().workArea
session
// Deprecated
ses.setCertificateVerifyProc((hostname, certificate, callback) => {
callback(true)
})
// Replace with
ses.setCertificateVerifyProc((request, callback) => {
callback(0)
})
Tray
// Deprecated
tray.setHighlightMode(true)
// Replace with
tray.setHighlightMode('on')
// Deprecated
tray.setHighlightMode(false)
// Replace with
tray.setHighlightMode('off')
webContents
// Deprecated
webContents.openDevTools({ detach: true })
// Replace with
webContents.openDevTools({ mode: 'detach' })
// Removed
webContents.setSize(options)
// There is no replacement for this API
webFrame
// Deprecated
webFrame.registerURLSchemeAsSecure('app')
// Replace with
protocol.registerStandardSchemes(['app'], { secure: true })
// Deprecated
webFrame.registerURLSchemeAsPrivileged('app', { secure: true })
// Replace with
protocol.registerStandardSchemes(['app'], { secure: true })
<webview>
// Removed
webview.setAttribute('disableguestresize', '')
// There is no replacement for this API
// Removed
webview.setAttribute('guestinstance', instanceId)
// There is no replacement for this API
// Keyboard listeners no longer work on webview tag
webview.onkeydown = () => { /* handler */ }
webview.onkeyup = () => { /* handler */ }
Node Headers URL
这是通过 .npmrc 文件中的 disturl 或在构建原生 Node 模块时通过命令行标志 --dist-url 指定的 URL。
已弃用:https://atom.io/download/atom-shell
替换为:https://atom.io/download/electron
重大 API 更改 (2.0)
下表列出了 Electron 2.0 中的重大 API 更改。
BrowserWindow
// Deprecated
const optionsA = { titleBarStyle: 'hidden-inset' }
const windowA = new BrowserWindow(optionsA)
// Replace with
const optionsB = { titleBarStyle: 'hiddenInset' }
const windowB = new BrowserWindow(optionsB)
menu
// 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
- 为了与其他由 Node 设置的
process.versions属性保持一致,process.versions.electron和process.version.chrome将被设为只读属性。
webContents
// Removed
webContents.setZoomLevelLimits(1, 2)
// Replaced with
webContents.setVisualZoomLevelLimits(1, 2)
webFrame
// Removed
webFrame.setZoomLevelLimits(1, 2)
// Replaced with
webFrame.setVisualZoomLevelLimits(1, 2)
<webview>
// Removed
webview.setZoomLevelLimits(1, 2)
// Replaced with
webview.setVisualZoomLevelLimits(1, 2)
重复的 ARM 资产
每个 Electron 版本都包含两个相同的 ARM 构建,文件名略有不同,例如 electron-v1.7.3-linux-arm.zip 和 electron-v1.7.3-linux-armv7l.zip。添加带有 v7l 前缀的资产是为了向用户明确其支持的 ARM 版本,并区分未来可能生成的 armv6l 和 arm64 资产。
文件名 *不带前缀* 的文件仍被发布,以避免破坏可能正在使用它的任何设置。从 2.0 版本开始,将不再发布不带前缀的文件。