破坏性变更
破坏性变更将在此处记录,并在 JS 代码中尽可能添加弃用警告,至少在进行更改前 一个主要版本。
破坏性变更类型
本文档使用以下约定来分类破坏性变更
- API 变更:API 已更改,以至于未更新的代码保证会抛出异常。
- 行为变更:Electron 的行为已更改,但不会必然抛出异常。
- 默认值变更:依赖旧默认值的代码可能会出错,不一定会抛出异常。可以通过显式指定值来恢复旧行为。
- 弃用:API 已标记为弃用。API 将继续工作,但会发出弃用警告,并在未来的版本中删除。
- 移除:API 或功能已被移除,不再受 Electron 支持。
计划中的破坏性 API 变更 (40.0)
弃用:渲染进程中的 clipboard API 访问
在渲染进程中直接使用 clipboard API 已被弃用。如果您想从渲染进程调用此 API,请将 API 调用放在您的预加载脚本中,并使用 contextBridge API 进行暴露。
行为变更:MacOS dSYM 文件现在使用 tar.xz 压缩
MacOS (dSYM) 的调试符号现在使用 xz 压缩,以便处理更大的文件大小。dsym.zip 文件现在是 dsym.tar.xz 文件。使用调试符号的最终用户可能需要更新他们的 zip 工具。
计划中的破坏性 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 会话中以本机 Wayland 应用程序运行(当 XDG_SESSION_TYPE=wayland 时)。用户可以通过传递 --ozone-platform=x11 来强制使用 XWayland。
移除:ORIGINAL_XDG_CURRENT_DESKTOP 环境变量
以前,Electron 内部将 XDG_CURRENT_DESKTOP 的值更改为 Unity,并将桌面会话的原始名称存储在一个单独的变量中。XDG_CURRENT_DESKTOP 不再被覆盖,现在反映了实际的桌面环境。
移除:macOS 11 支持
macOS 11 (Big Sur) 不再受 Chromium 支持。
旧版本的 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 将会发出一条错误消息警告,而不是使进程崩溃。
要恢复以前的行为,您可以使用
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 现在支持 WebUSB 阻止列表 和 Web Serial 阻止列表,这些阻止列表由 Chromium 使用并概述在其各自的规范中。
要禁用这些功能,用户可以传递 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 不再受支持,因为它已被 上游 Chromium 删除。
弃用: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 仅支持 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。在使用 portal 文件选择器对话框时,除非 portal 后端版本为 4 或更高版本,否则不支持使用 Dialog API 的 defaultPath 选项。可以使用 --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 上触发此 API 的权限检查和关联的权限类型 deprecated-sync-clipboard-read 的 enableDeprecatedPaste 选项也已被弃用。
行为变更:框架属性可能会检索分离的 WebFrameMain 实例或根本不检索
提供对 WebFrameMain 实例访问权限的 API 可能会返回一个 frame.detached 设置为 true 的实例,或者可能返回 null。
当框架执行跨域导航时,它将进入一个分离状态,在该状态下它不再附加到页面。在此状态下,它可能正在运行 unload 处理程序,然后再被删除。如果在这种状态下发送 IPC,则 frame.detached 将设置为 true,框架随后将被销毁。
在接收到事件时,立即访问 WebFrameMain 属性非常重要。否则,无法保证它指向与接收时相同的网页。为了避免不一致的期望,Electron 将在网页已更改的情况下返回 null。
ipcMain.on('unload-event', (event) => {
event.senderFrame // ✅ accessed immediately
})
ipcMain.on('unload-event', async (event) => {
await crossOriginNavigationPromise
event.senderFrame // ❌ returns `null` due to late access
})
行为变更:Windows 上的自定义协议 URL 处理
由于 Chromium 为了支持 非特殊方案 URL 而做出的变更,使用 Windows 文件路径的自定义协议 URL 将不再能与已弃用的 protocol.registerFileProtocol 以及 BrowserWindow.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 属性在事件由使用 respondToAuthRequestsFromMainProcess 选项创建的 实用进程 请求触发时将为 null。
弃用:BrowserWindowConstructorOption.type 中的 textured 选项
BrowserWindowConstructorOptions 中 type 的 textured 选项已被弃用,没有替代方案。此选项依赖于 macOS 上的 NSWindowStyleMaskTexturedBackground 样式掩码,该样式掩码已被弃用,没有替代方案。
移除:macOS 10.15 支持
macOS 10.15 (Catalina) 不再受 Chromium 的支持。
旧版本的 Electron 将继续在 Catalina 上运行,但运行 Electron v33.0.0 及更高版本需要 macOS 11 (Big Sur) 或更高版本。
行为变更:原生模块现在需要 C++20
由于上游变更,V8 和 Node.js 现在需要 C++20 作为最低版本。使用原生 node 模块的开发者应使用 --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}`)
}
})
已弃用:clearHistory、canGoBack、goBack、canGoForward、goForward、goToIndex、canGoToOffset、goToOffset 在 WebContents 上
这些与导航相关的 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 目录将被删除
当 Electron 32 首次运行时,如果 app.getPath('userData') 返回的目录中存在名为 databases 的目录,它将被删除。 databases 目录由 WebSQL 使用,WebSQL 已在 Electron 31 中删除。Chromium 现在执行清理操作以删除此目录。请参阅 issue #45396。
计划中的破坏性 API 变更 (31.0)
已移除:WebSQL 支持
Chromium 已在上游移除了对 WebSQL 的支持,并将其过渡到仅限 Android。有关更多信息,请参阅 Chromium 移除意向讨论。
行为变更:nativeImage.toDataURL 将保留 PNG 色彩空间
PNG 解码器实现已更改为保留色彩空间数据,此函数返回的编码数据现在与其匹配。
有关更多信息,请参阅 crbug.com/332584706。
行为变更:window.flashFrame(bool) 在 macOS 上将持续闪烁 Dock 图标
这使行为与 Windows 和 Linux 保持一致。之前的行为:第一次 flashFrame(true) 仅使 Dock 图标弹跳一次(使用 NSInformationalRequest 级别),而 flashFrame(false) 什么也不做。新的行为:持续闪烁,直到调用 flashFrame(false) 为止。这使用了 NSCriticalRequest 级别。要显式使用 NSInformationalRequest 以导致 Dock 图标单次弹跳,仍然可以使用 dock.bounce('informational')。
计划中的破坏性 API 变更 (30.0)
行为变更:跨域 iframe 现在使用权限策略来访问功能
跨域 iframe 现在必须通过 allow 属性指定可用于给定 iframe 的功能,才能访问它们。
有关更多信息,请参阅 文档。
已移除:--disable-color-correct-rendering 开关
此开关从未正式记录,但无论如何也在此处记录其移除。
行为变更:macOS 上的 BrowserView.setAutoResize 行为
在 Electron 30 中,BrowserView 现在是围绕新的 WebContentsView API 的包装器。
此前,BrowserView API 的 setAutoResize 函数由 macOS 上的 autoresizing 支持,以及 Windows 和 Linux 上的自定义算法支持。对于简单的用例,例如使 BrowserView 填充整个窗口,这两种方法的行为是相同的。但是,在更高级的用例中,BrowserView 在 macOS 上的自动调整大小方式与在其他平台上的方式不同,因为 Windows 和 Linux 的自定义调整大小算法与 macOS 的自动调整大小 API 的行为并不完全匹配。现在,自动调整大小行为在所有平台上都已标准化。
如果您的应用程序使用 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 支持
macOS 10.13 (High Sierra) 和 macOS 10.14 (Mojave) 已不再受 Chromium 支持。
旧版本的 Electron 将继续在这些操作系统上运行,但运行 Electron v27.0.0 及更高版本将需要 macOS 10.15 (Catalina) 或更高版本。
已弃用:ipcRenderer.sendTo()
ipcRenderer.sendTo() API 已被弃用。应使用在渲染器之间设置 MessageChannel 来代替。
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 选项
已移除以下活力选项
- '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 上的可拖动区域
为了与 Windows 和 Linux 保持一致,macOS 上使用 CSS 属性 -webkit-app-region: drag 实现可拖动区域的方式已更改。 之前,当具有 -webkit-app-region: no-drag 的区域与具有 -webkit-app-region: drag 的区域重叠时,无论 CSS 分层如何,macOS 上的 no-drag 区域始终优先。 也就是说,如果 drag 区域位于 no-drag 区域之上,则会被忽略。 从 Electron 23 开始,drag 区域位于 no-drag 区域之上将正确导致该区域可拖动。
此外,之前创建忽略 -webkit-app-region CSS 属性的拖动区域的 customButtonsOnHover BrowserWindow 属性已得到修复 (有关讨论,请参阅 #37210)。
因此,如果您的应用程序使用带有可拖动区域的无边框窗口在 macOS 上,则您的应用程序中可拖动的区域可能会在 Electron 23 中发生变化。
移除:Windows 7 / 8 / 8.1 支持
Windows 7、Windows 8 和 Windows 8.1 已不再受支持。 Electron 遵循计划中的 Chromium 弃用策略,该策略将于 2023 年初开始 弃用 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 事件
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 内存笼已被启用,这会对使用 ArrayBuffer 或 Buffer 包装非 V8 内存的 native 模块产生影响。有关更多详细信息,请参阅 关于 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 支持
macOS 10.11 (El Capitan) 和 macOS 10.12 (Sierra) 不再受 Chromium 的支持。
较旧版本的 Electron 将继续在这些操作系统上运行,但要运行 Electron v20.0.0 及更高版本,需要 macOS 10.13 (High Sierra) 或更高版本。
默认变更:没有 nodeIntegration: true 的渲染器默认情况下被沙箱化
以前,指定了预加载脚本的渲染器默认未沙盒化。这意味着默认情况下,预加载脚本可以访问 Node.js。在 Electron 20 中,此默认设置已更改。从 Electron 20 开始,除非指定了 nodeIntegration: true 或 sandbox: false,否则渲染器默认将已沙盒化。
如果您的 preload 脚本不依赖 Node,则无需采取任何操作。如果您的 preload 脚本确实依赖 Node,请将其重构以删除渲染器中的 Node 用法,或者为相关的渲染器显式指定 sandbox: false。
移除:Linux 上的 skipTaskbar
在 X11 上,skipTaskbar 会向 X11 窗口管理器发送一个 _NET_WM_STATE_SKIP_TASKBAR 消息。Wayland 没有直接的等效项,并且已知的解决方法存在不可接受的权衡(例如,GNOME 中的 Window.is_skip_taskbar 需要不安全模式),因此 Electron 无法在 Linux 上支持此功能。
API 变更:session.setDevicePermissionHandler(handler)
当使用 session.setDevicePermissionHandler(handler) 时调用的处理程序对其参数进行了更改。该处理程序不再传递一个 WebFrameMain 框架,而是传递 origin,即正在检查设备权限的源。
计划中的破坏性 API 变更 (19.0)
移除:IA32 Linux 二进制文件
这是 Chromium 102.0.4999.0 停止支持 IA32 Linux 的结果。这标志着 移除对 IA32 Linux 支持 的结束。
计划中的破坏性 API 变更 (18.0)
移除:nativeWindowOpen
在 Electron 15 之前,window.open 默认使用 BrowserWindowProxy 进行模拟。这意味着 window.open('about:blank') 无法打开可同步脚本编写的子窗口,以及其他不兼容之处。自 Electron 15 起,nativeWindowOpen 已默认启用。
有关更多详细信息,请参阅 Electron 中的 window.open。
计划中的破坏性 API 变更 (17.0)
移除:渲染器中的 desktopCapturer.getSources
desktopCapturer.getSources API 现在仅在主进程中可用。为了提高 Electron 应用程序的默认安全性,进行了此更改。
如果您需要此功能,可以按如下方式替换它
// Main process
const { ipcMain, desktopCapturer } = require('electron')
ipcMain.handle(
'DESKTOP_CAPTURER_GET_SOURCES',
(event, opts) => desktopCapturer.getSources(opts)
)
// Renderer process
const { ipcRenderer } = require('electron')
const desktopCapturer = {
getSources: (opts) => ipcRenderer.invoke('DESKTOP_CAPTURER_GET_SOURCES', opts)
}
但是,您应该考虑进一步限制返回给渲染器的信息;例如,向用户显示源选择器,并仅返回所选源。
已弃用:nativeWindowOpen
在 Electron 15 之前,window.open 默认使用 BrowserWindowProxy 进行模拟。这意味着 window.open('about:blank') 无法打开可同步脚本编写的子窗口,以及其他不兼容之处。自 Electron 15 起,nativeWindowOpen 已默认启用。
有关更多详细信息,请参阅 Electron 中的 window.open。
计划中的破坏性 API 变更 (16.0)
行为变更:在 Linux 上切换到 Crashpad 的 crashReporter 实现
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 默认情况下被 shimmed 以使用 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 时,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()
请使用会话 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 标头上传到崩溃摄取服务器,并且主体将被压缩。
如果您的崩溃摄取服务器不支持压缩有效负载,可以通过在崩溃报告器选项中指定 { 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
}
})
我们 建议停止使用 remote 模块。
protocol.unregisterProtocol
protocol.uninterceptProtocol
这些 API 现在是同步的,可选的回调函数不再需要。
// Deprecated
protocol.unregisterProtocol(scheme, () => { /* ... */ })
// Replace with
protocol.unregisterProtocol(scheme)
protocol.registerFileProtocol
protocol.registerBufferProtocol
protocol.registerStringProtocol
protocol.registerHttpProtocol
protocol.registerStreamProtocol
protocol.interceptFileProtocol
protocol.interceptStringProtocol
protocol.interceptBufferProtocol
protocol.interceptHttpProtocol
protocol.interceptStreamProtocol
这些 API 现在是同步的,可选的回调函数不再需要。
// Deprecated
protocol.registerFileProtocol(scheme, handler, () => { /* ... */ })
// Replace with
protocol.registerFileProtocol(scheme, handler)
注册或拦截的协议在发生导航之前不会对当前页面产生影响。
protocol.isProtocolHandled
此 API 已弃用,用户应改用 protocol.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()
请使用会话 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 发送函数、Promise、WeakMap、WeakSet 或包含任何此类值的对象现在将抛出异常,而不是将函数静默转换为
undefined。
// Previously:
ipcRenderer.send('channel', { value: 3, someFunction: () => {} })
// => results in { value: 3 } arriving in the main process
// From Electron 8:
ipcRenderer.send('channel', { value: 3, someFunction: () => {} })
// => throws Error("() => {} could not be cloned.")
NaN、Infinity和-Infinity现在将被正确序列化,而不是转换为null。- 包含循环引用的对象现在将被正确序列化,而不是转换为
null。 Set、Map、Error和RegExp值将被正确序列化,而不是转换为{}。BigInt值将被正确序列化,而不是转换为null。- 稀疏数组将被序列化为稀疏数组,而不是转换为带有
null的密集数组。 Date对象将作为Date对象传输,而不是转换为其 ISO 字符串表示形式。- Typed Array(例如
Uint8Array、Uint16Array、Uint32Array等)将作为 Typed Array 传输,而不是转换为 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
此 URL 在 .npmrc 文件中指定为 disturl,或者在构建本机 Node 模块时作为 --dist-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 中,这将返回一个包含 File 对象的 FileList,用于
path/to/folder
在 Electron 7 中,现在返回一个包含 File 对象的 FileList,用于
/path/to/folder/file3
/path/to/folder/file2
/path/to/folder/file1
请注意,webkitdirectory 不再暴露所选文件夹的路径。如果您需要所选文件夹的路径而不是文件夹内容,请参阅 dialog.showOpenDialog API (链接)。
API 变更:承诺化 API 的基于回调的版本
Electron 5 和 Electron 6 引入了现有异步 API 的基于 Promise 的版本,并弃用了其较旧的基于回调的对应版本。在 Electron 7 中,所有弃用的基于回调的 API 都已移除。
这些函数现在仅返回 Promise
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 变更:现在必须在应用准备就绪之前注册特权模式
渲染进程 API webFrame.registerURLSchemeAsPrivileged 和 webFrame.registerURLSchemeAsBypassingCSP 以及浏览器进程 API protocol.registerStandardSchemes 已被移除。已添加新的 API protocol.registerSchemesAsPrivileged,应将其用于使用所需权限注册自定义模式。需要在使用应用准备就绪之前注册自定义模式。
已弃用:webFrame.setIsolatedWorld* 替换为 webFrame.setIsolatedWorldInfo
// Deprecated
webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp)
webFrame.setIsolatedWorldHumanReadableName(worldId, name)
webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin)
// Replace with
webFrame.setIsolatedWorldInfo(
worldId,
{
securityOrigin: 'some_origin',
name: 'human_readable_name',
csp: 'content_security_policy'
})
API 变更:webFrame.setSpellCheckProvider 现在接受异步回调
spellCheck 回调现在是异步的,并且已移除 autoCorrectWord 参数。
// Deprecated
webFrame.setSpellCheckProvider('en-US', true, {
spellCheck: (text) => {
return !spellchecker.isMisspelled(text)
}
})
// Replace with
webFrame.setSpellCheckProvider('en-US', {
spellCheck: (words, callback) => {
callback(words.filter(text => spellchecker.isMisspelled(text)))
}
})
API 变更:webContents.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 开始,将不再发布不带前缀的文件。