破坏性变更
重大更改将在此处记录,并在可能的情况下,在 JS 代码中添加弃用警告,至少在更改 一个主版本之前。
重大更改的类型
本文档使用以下约定来分类重大更改
- API 已更改: API 的更改方式是,未经更新的代码一定会抛出异常。
- 行为已更改: Electron 的行为已发生变化,但不一定会抛出异常。
- 默认值已更改: 依赖旧默认值的代码可能会中断,不一定会抛出异常。通过显式指定值可以恢复旧行为。
- 已弃用: API 已标记为已弃用。API 将继续工作,但会发出弃用警告,并在未来的版本中移除。
- 已移除: API 或功能已被移除,不再受 Electron 支持。
计划中的重大 API 更改 (37.0)
Utility Process 未处理的拒绝行为更改
现在,当发生未处理的拒绝时,Utility Process 将会发出一条错误消息警告,而不是使进程崩溃。
要恢复以前的行为,您可以使用
process.on('unhandledRejection', () => {
process.exit(1)
})
行为已更改:process.exit()
同步终止 utility process
在实用工具进程中调用 process.exit()
现在将同步终止该进程。这使得 process.exit()
的行为与 Node.js 的行为保持一致。
请参考 Node.js 文档和 PR #45690 来了解其潜在影响,例如在调用 process.exit()
之前调用 console.log()
。
行为已更改:WebUSB 和 WebSerial 阻止列表支持
WebUSB 和 Web Serial 现在支持 Chromium 使用的 WebUSB 阻止列表和 Web Serial 阻止列表,并在其各自的规范中进行了概述。
要禁用这些功能,用户可以传递 disable-usb-blocklist
和 disable-serial-blocklist
作为命令行标志。
已移除:ProtocolResponse
中 session
属性的 null
值
这个已弃用的功能已被移除。
以前,将 ProtocolResponse.session
属性设置为 null
会创建一个随机的独立会话。这已不再受支持。
此处建议不使用仅用于单个目的的 session,因为这会产生额外的开销;但是,需要保留此行为的旧代码可以通过创建随机 session (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。此功能不再支持。
此处建议不使用仅用于单个目的的 session,因为这会产生额外的开销;但是,需要保留此行为的旧代码可以通过创建随机 session (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+,而 Windows 10+ 已无法禁用 DWM 合成。
已更改:GNOME 运行时默认为 GTK 4
在 上游更改后,GNOME 运行时现在默认使用 GTK 4。
在极少数情况下,这可能会导致某些应用程序或配置出错,并显示以下消息:
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 文件选择器对话框时不支持该选项,除非 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")
" title="直接链接到 已弃用: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
属性
当事件由使用 respondToAuthRequestsFromMainProcess
选项创建的 utility process 触发时,来自 app
的 login
事件中的 webContents
属性将为 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 模块的开发者应使用 --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 使用,而 WebSQL 在 Electron 31 中已被移除。Chromium 现在执行清理操作,删除此目录。请参阅 issue #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 的封装。
以前,BrowserView
API 的 setAutoResize
函数在 macOS 上由 autoresizing 支持,而在 Windows 和 Linux 上由自定义算法支持。对于简单的用例,例如使 BrowserView 填满整个窗口,这两种方法的行为是相同的。但是,在更高级的用例中,BrowserView 在 macOS 上的 autoresize 会与在其他平台上的 autoresize 不同,因为 Windows 和 Linux 的自定义调整大小算法与 macOS 的 autoresizing API 的行为不完全匹配。现在,所有平台上的 autoresize 行为都已标准化。
如果您的应用程序使用 BrowserView.setAutoResize
来执行比使 BrowserView 填满整个窗口更复杂的操作,那么您可能已经添加了自定义逻辑来处理 macOS 上的这种行为差异。如果是这样,这些逻辑在 Electron 30 中将不再需要,因为 autoresize 行为是一致的。
已弃用:BrowserView
BrowserView
类已被弃用,取而代之的是新的 WebContentsView
类。
BrowserWindow
中与 BrowserView
相关的 API 也已被弃用
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
发送
尝试将整个 ipcRenderer
模块作为对象通过 contextBridge
发送,现在将在桥的接收端得到一个空对象。此更改是为了消除/缓解一个不安全的陷阱。您不应直接通过桥公开 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-changed
high-contrast-color-scheme-changed
请改用 nativeTheme
模块上新的 updated
事件。
// Removed
systemPreferences.on('inverted-color-scheme-changed', () => { /* ... */ })
systemPreferences.on('high-contrast-color-scheme-changed', () => { /* ... */ })
// Replace with
nativeTheme.on('updated', () => { /* ... */ })
已移除:macOS 上 window.setVibrancy
的部分选项
以下 vibrancy 选项已被移除
- 'light'
- 'medium-light'
- 'dark'
- 'ultra-dark'
- 'appearance-based'
这些选项之前已被弃用,并在 10.15 中被 Apple 移除。
已移除: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
替换。请参阅 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
,以反映传递的 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 的计划弃用策略,该策略 将在 2023 年初弃用 Windows 7 的支持(从 Chromium 109 开始)。
旧版本的 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
移除了参数
printSelectionOnly
marginsType
headerFooter
scaleFactor
添加了参数
headerTemplate
footerTemplate
displayHeaderFooter
margins
scale
preferCSSPageSize
// Main process
const { webContents } = require('electron')
webContents.printToPDF({
landscape: true,
displayHeaderFooter: true,
printBackground: true,
scale: 2,
pageSize: 'Ledger',
margins: {
top: 2,
bottom: 2,
left: 2,
right: 2
},
pageRanges: '1-5, 8, 11-13',
headerTemplate: '<h1>Title</h1>',
footerTemplate: '<div><span class="pageNumber"></span></div>',
preferCSSPageSize: true
}).then(data => {
fs.writeFile(pdfPath, data, (error) => {
if (error) throw error
console.log(`Wrote PDF successfully to ${pdfPath}`)
})
}).catch(error => {
console.log(`Failed to write PDF to ${pdfPath}: `, error)
})
计划中的重大 API 更改 (20.0)
已移除:macOS 10.11 / 10.12 支持
macOS 10.11 (El Capitan) 和 macOS 10.12 (Sierra) 不再受 Chromium 支持。
旧版本的 Electron 将继续在这些操作系统上运行,但运行 Electron v20.0.0 及更高版本将需要 macOS 10.13 (High Sierra) 或更高版本。
默认值已更改:未设置 nodeIntegration: true
的渲染器默认处于沙盒模式
以前,指定了预加载脚本的渲染器默认处于非沙盒模式。这意味着默认情况下,预加载脚本可以访问 Node.js。在 Electron 20 中,此默认值已更改。从 Electron 20 开始,渲染器将默认处于沙盒模式,除非指定了 nodeIntegration: 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.shouldUseDarkColors
nativeTheme.shouldUseInvertedColorScheme
nativeTheme.shouldUseHighContrastColors
// Removed in Electron 13
systemPreferences.isDarkMode()
// Replace with
nativeTheme.shouldUseDarkColors
// Removed in Electron 13
systemPreferences.isInvertedColorScheme()
// Replace with
nativeTheme.shouldUseInvertedColorScheme
// Removed in Electron 13
systemPreferences.isHighContrastColorScheme()
// Replace with
nativeTheme.shouldUseHighContrastColors
已弃用:WebContents new-window
事件
WebContents 的 new-window
事件已被弃用。它被 webContents.setWindowOpenHandler()
取代。
// Deprecated in Electron 13
webContents.on('new-window', (event) => {
event.preventDefault()
})
// Replace with
webContents.setWindowOpenHandler((details) => {
return { action: 'deny' }
})
计划中的重大 API 更改 (12.0)
已移除:Pepper Flash 支持
Chromium 已移除对 Flash 的支持,因此我们也必须遵循。请参阅 Chromium 的 Flash Roadmap 了解更多详情。
默认值已更改:worldSafeExecuteJavaScript
默认为 true
在 Electron 12 中,worldSafeExecuteJavaScript
将默认启用。要恢复之前的行为,必须在 WebPreferences 中指定 worldSafeExecuteJavaScript: false
。请注意,将此选项设置为 false
是不安全的。
此选项将在 Electron 14 中移除,请迁移您的代码以支持默认值。
默认值已更改:contextIsolation
默认为 true
在 Electron 12 中,contextIsolation
将默认启用。要恢复之前的行为,必须在 WebPreferences 中指定 contextIsolation: false
。
我们 建议启用 contextIsolation 以确保应用程序的安全性。
另一个影响是,除非 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.start
crashReporter.getLastCrashReport
crashReporter.getUploadedReports
crashReporter.getUploadToServer
crashReporter.setUploadToServer
crashReporter.getCrashesDirectory
它们只能从主进程调用。
有关更多详细信息,请参阅 #23265。
默认值已更改:crashReporter.start({ compress: true })
crashReporter.start
的 compress
选项的默认值已从 false
更改为 true
。这意味着 crash dump 将以 Content-Encoding: gzip
头部上传到 crash 接收服务器,并且主体将被压缩。
如果您的 crash 接收服务器不支持压缩负载,可以通过在 crash 报告器选项中指定 { 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.start
crashReporter.getLastCrashReport
crashReporter.getUploadedReports
crashReporter.getUploadToServer
crashReporter.setUploadToServer
crashReporter.getCrashesDirectory
crashReporter
模块在渲染器中唯一非弃用的方法是 addExtraParameter
、removeExtraParameter
和 getParameters
。
在主进程中调用所有上述方法仍然是非弃用的。
有关更多详细信息,请参阅 #23265。
已弃用:crashReporter.start({ compress: false })
在 crashReporter.start
中设置 { compress: false }
已被弃用。几乎所有 crash 接收服务器都支持 gzip 压缩。此选项将在未来的 Electron 版本中移除。
默认值已更改:enableRemoteModule
默认为 false
在 Electron 9 中,使用 remote 模块而不通过 WebPreferences 选项 enableRemoteModule
显式启用它时,开始发出警告。在 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()
请使用 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 倍的性能提升,但也带来了一些行为上的重大变更。
- 发送函数、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 字符串表示形式。- 类型化数组(例如
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 中,这些对象将按原样序列化并显示弃用警告消息,但从 Electron 9 开始,发送此类对象将抛出“无法克隆”错误。
已弃用:<webview>.getWebContents()
此 API 使用 remote
模块实现,该模块存在性能和安全风险。因此,应明确使用它。
// Deprecated
webview.getWebContents()
// Replace with
const { remote } = require('electron')
remote.webContents.fromId(webview.getWebContentsId())
然而,建议完全避免使用 remote
模块。
// main
const { ipcMain, webContents } = require('electron')
const getGuestForWebContents = (webContentsId, contents) => {
const guest = webContents.fromId(webContentsId)
if (!guest) {
throw new Error(`Invalid webContentsId: ${webContentsId}`)
}
if (guest.hostWebContents !== contents) {
throw new Error('Access denied to webContents')
}
return guest
}
ipcMain.handle('openDevTools', (event, webContentsId) => {
const guest = getGuestForWebContents(webContentsId, event.sender)
guest.openDevTools()
})
// renderer
const { ipcRenderer } = require('electron')
ipcRenderer.invoke('openDevTools', webview.getWebContentsId())
已弃用:webFrame.setLayoutZoomLevelLimits()
Chromium 已移除对更改布局缩放级别限制的支持,Electron 无法维护此功能。该函数在 Electron 8.x 中会发出警告,并在 Electron 9.x 中消失。布局缩放级别限制现已固定为最低 0.25 和最高 5.0,此处定义了这些限制。
systemPreferences
中已弃用的事件
以下 systemPreferences
事件已被弃用
inverted-color-scheme-changed
high-contrast-color-scheme-changed
请改用 nativeTheme
模块上新的 updated
事件。
// Deprecated
systemPreferences.on('inverted-color-scheme-changed', () => { /* ... */ })
systemPreferences.on('high-contrast-color-scheme-changed', () => { /* ... */ })
// Replace with
nativeTheme.on('updated', () => { /* ... */ })
已弃用:systemPreferences
中的方法
以下 systemPreferences
方法已被弃用
systemPreferences.isDarkMode()
systemPreferences.isInvertedColorScheme()
systemPreferences.isHighContrastColorScheme()
请改用以下 nativeTheme
属性
nativeTheme.shouldUseDarkColors
nativeTheme.shouldUseInvertedColorScheme
nativeTheme.shouldUseHighContrastColors
// Deprecated
systemPreferences.isDarkMode()
// Replace with
nativeTheme.shouldUseDarkColors
// Deprecated
systemPreferences.isInvertedColorScheme()
// Replace with
nativeTheme.shouldUseInvertedColorScheme
// Deprecated
systemPreferences.isHighContrastColorScheme()
// Replace with
nativeTheme.shouldUseHighContrastColors
计划中的重大 API 变更 (7.0)
已弃用:Atom.io Node 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 都已被移除。
这些函数现在仅返回 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 变更:注册特权 scheme 现在必须在 app ready 之前完成
渲染器进程 API webFrame.registerURLSchemeAsPrivileged
和 webFrame.registerURLSchemeAsBypassingCSP
以及浏览器进程 API protocol.registerStandardSchemes
已被移除。已添加了一个新 API protocol.registerSchemesAsPrivileged
,应使用它来注册具有所需特权的自定义 scheme。自定义 scheme 必须在 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 上加载失败,并显示类似“找不到模块”的错误消息。更多信息请参阅原生模块指南。
已移除: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 开始,将不再发布无前缀的文件。