重大更改

优质
小牛编辑
142浏览
2023-12-01

这里将记录重大更改,并在可能的情况下向JS代码添加弃用警告,在这更改之前至少会有一个重要版本.

重大更改的类型

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

  • API 更改:已更改的 API 会以某种方式使未更新的代码必定抛出异常。
  • 行为改变:Electron 的行为已经改变,但并不一定抛出相应的异常。
  • 默认值更改:依赖于默认值的代码的行为可能被破坏,但不保证会抛出相应的异常。 您可以通过显式指定该值的方式恢复旧的默认行为。
  • 已废弃:该 API 已标记为废弃。 该 API 依旧可正常运作,但会抛出已废弃警告,并在将来会移除。
  • 已移除:该 API 或功能已移除,Electron团队不再对此提供支持。

计划重写的 API (15.0)

默认更改: nativeWindowOpen 默认为 true

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

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

计划重写的 API (14.0)

Removed: remote module

The remote module was deprecated in Electron 12, and will be removed in Electron 14. 由@electronic/remote 模块替代。

// Deprecated in Electron 12:
const { BrowserWindow } = require('electron').remote
// 替换为:
const { BrowserWindow } = require('@electron/remote')

// 在主进程中:
require('@electron/remote/main').initialize()

已移除: app.allowRendererProcessReuse

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

For more detailed information see #18397.

Removed: Browser Window Affinity

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

For more detailed information see #18397.

API 更改: window.open()

可选参数 frameName 将不再设置窗口的标题。 该功能现在遵循 原生文档 中的约束,由名为 windowName 的参数控制。

若您之前使用了该参数用于设置窗口标题,您可以转而使用 win.setTitle(title)

已移除: worldSafeExecuteJavaScript

在 Electron 14, worldSafeExecuteJavaScript 将被移除。 除此之外没有其他方式,请保证您的代码中包含该属性。 Electron 12中默认启用该属性。 12.

若您使用了 webFrame.executeJavaScriptwebFrame.executeJavaScriptInIsolatedWorld,这个改动会对您造成影响。 您需要保证 Context Bridge API 支持这些方法的返回值,因为这些方法使用相同的值传递语义。

Removed: BrowserWindowConstructorOptions inheriting from parent windows

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

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

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

已移除: additionalFeatures

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

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

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

计划重写的 API (13.0)

API 更改: session.setPermissionCheckHandler(handler)

handler 方法的第一个参数曾是 webContents,但现在可以为 null。 为正确响应权限检查,您需要使用requestingOriginembeddingOriginsecurityOrigin 这些属性。 因为 webContents 现在可能为 null,您不应当依赖此参数。

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

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

已移除: shell.moveItemToTrash()

已废弃的同步方法 shell.moveItemToTrash() 已移除。 作为替代,您应当使用异步的 shell.trashItem()

// 在 Electron 13 移除
shell.moveItemToTrash(path)
// 替换为
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()
// 在 Electron 13 移除
BrowserWindow.addExtension(path)
BrowserWindow.addDevToolsExtension(path)
// 替换为
session.defaultSession.loadExtension(path)
// 在 Electron 13 移除
BrowserWindow.removeExtension(name)
BrowserWindow.removeDevToolsExtension(name)
// 替换为
session.defaultSession.removeExtension(extension_id)
// 在 Electron 13 移除
BrowserWindow.getExtensions()
BrowserWindow.getDevToolsExtensions()
// 替换为
session.defaultSession.getAllExtensions()

已移除: systemPreferences 中的方法

systemPreferences 方法已经被废弃:

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

使用 nativeTheme 属性作为替代:

  • nativeTheme.shouldUseDarkColors
  • nativeTheme.shouldUseInvertedColorScheme
  • nativeTheme.shouldUseHighContrastColors
// 在 Electron 13 移除
systemPreferences.isDarkMode()
// 替换为
nativeTheme.shouldUseDarkColors

// 在 Electron 13 移除
systemPreferences.isInvertedColorScheme()
// 替换为
nativeTheme.shouldUseInvertedColorScheme

// 在 Electron 13 移除
systemPreferences.isHighContrastColorScheme()
// 替换为
nativeTheme.shouldUseHighContrastColors

已废弃: WebContents new-window 事件

WebContents 中的 new-window 事件已经被废弃。 已弃用:webContents.setWindowOpenHandler()

// 在 Electron 13 废弃
webContents.on('new-window', (event) => {
  event.preventDefault()
})

// 替换为
webContents.setWindowOpenHandler((details) => {
  return { action: 'deny' }
})

计划重写的 API (12.0)

已移除:Pepper Flash 支持

Chromium 已经取消了对Flash的支持,因此我们必须效仿。 更多详细信息,请参阅 Chromium 的 Flash Roadmap

默认更改: worldSafeExecuteJavaScript 默认为 true

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

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

默认更改: contextIsolation 默认为 true

在 Electron 12, contextIsolation 将默认启用。 要恢复 上一个行为, contextIsolation: false 必须在 Web 首选项中指定。

我们 建议启用contextIsolation ,以保证您的应用程序的安全性。

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

更多信息请参阅:https://github.com/electron/electron/issues/23506

已移除: crashReporter.getCrashesDirectory()

crashReporter.getCrashesDirectory 方法已被删除。 这个方法 应该被 app.getPath('crashDumps')替换。

// 在 Electron 12 移除
crashReporter.getCrashesDirectory()
// 替换为
app.getPath('crashDumps')

Removed: crashReporter methods in the renderer process

crashReporter 方法在渲染进程中不再能使用:

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

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

更多详细信息请访问 #23265

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

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

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

已废弃: remote 模块

remote 模块在 Electron 12 废弃,并将在 Electron 14 被移除 由@electronic/remote 模块替代。

// Deprecated in Electron 12:
const { BrowserWindow } = require('electron').remote
// 替换为:
const { BrowserWindow } = require('@electron/remote')

// 在主进程中:
require('@electron/remote/main').initialize()

已废弃:shell.moveItemToTrash()

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

// 在 Electron 12 废弃
shell.moveItemToTrash(path)
// 替换为
shell.trashItem(path).then(/* ... */)

计划重写的 API (11.0)

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

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

For more detailed information, see #23578.

计划重写的 API (10.0)

Deprecated: companyName argument to crashReporter.start()

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

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

已废弃:crashReporter.getCrashesDirectory()

The crashReporter.getCrashesDirectory method has been deprecated. 这个方法 应该被 app.getPath('crashDumps')替换。

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

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

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

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

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

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

更多详细信息请访问 #23265

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

Setting { compress: false } in crashReporter.start is deprecated. Nearly all crash ingestion servers support gzip compression. 此选项将在未来版本的 Electron 中删除。

默认更改: enableRemoteModule 默认为 false

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

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

We recommend moving away from the remote module.

protocol.unregisterProtocol

protocol.uninterceptProtocol

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

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

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

// 已废弃
protocol.registerFileProtocol(scheme, handler, () => { /* ... */ })
// 替换为
protocol.registerFileProtocol(scheme, handler)

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

protocol.isProtocolHandled

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

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

计划重写的 API (9.0)

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

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

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

For more detailed information see #18397.

已废弃: BrowserWindow 扩展 API

以下扩展 APIs 已废弃:

  • 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()
// 在 Electron 9 废弃
BrowserWindow.addExtension(path)
BrowserWindow.addDevToolsExtension(path)
// 替换为
session.defaultSession.loadExtension(path)
// 在 Electron 9 废弃
BrowserWindow.removeExtension(name)
BrowserWindow.removeDevToolsExtension(name)
// 替换为
session.defaultSession.removeExtension(extension_id)
// 在 Electron 9 废弃
BrowserWindow.getExtensions()
BrowserWindow.getDevToolsExtensions()
// 替换为
session.defaultSession.getAllExtensions()

已移除: <webview>.getWebContents()

此API在 Electron 8.0中被废弃,现已删除。

// 在 Electron 9.0 移除
webview.getWebContents()
// 替换为
const { remote } = require('electron')
remote.webContents.fromId(webview.getWebContentsId())

已移除: webFrame.setLayoutZoomLevelLimits()

Chromium has removed support for changing the layout zoom level limits, and it is beyond Electron's capacity to maintain it. 函数在 Electron 8.x 废弃,并将在 Electron 9.x 被移除。 The layout zoom level limits are now fixed at a minimum of 0.25 and a maximum of 5.0, as defined here.

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

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

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

API Changed: shell.openItem is now shell.openPath

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

计划重写的 API (8.0)

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

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

  • Sending Functions, Promises, WeakMaps, WeakSets, or objects containing any such values, over IPC will now throw an exception, instead of silently converting the functions to 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 and -Infinity will now be correctly serialized, instead of being converted to null.
  • Objects containing cyclic references will now be correctly serialized, instead of being converted to null.
  • Set, Map, Error and RegExp values will be correctly serialized, instead of being converted to {}.
  • BigInt values will be correctly serialized, instead of being converted to null.
  • Sparse arrays will be serialized as such, instead of being converted to dense arrays with nulls.
  • Date objects will be transferred as Date objects, instead of being converted to their ISO string representation.
  • Typed Arrays (such as Uint8Array, Uint16Array, Uint32Array and so on) will be transferred as such, instead of being converted to Node.js Buffer.
  • Node.js Buffer objects will be transferred as Uint8Arrays. You can convert a Uint8Array back to a Node.js Buffer by wrapping the underlying ArrayBuffer:
Buffer.from(value.buffer, value.byteOffset, value.byteLength)

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

已废弃: <webview>.getWebContents()

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

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

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

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

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

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

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

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

Deprecated: webFrame.setLayoutZoomLevelLimits()

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

Deprecated events in systemPreferences

The following systemPreferences events have been deprecated:

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

Use the new updated event on the nativeTheme module instead.

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

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

已废弃:systemPreferences 中的方法

systemPreferences 方法已经被废弃:

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

使用 nativeTheme 属性作为替代:

  • nativeTheme.shouldUseDarkColors
  • nativeTheme.shouldUseInvertedColorScheme
  • nativeTheme.shouldUseHighContrastColors
// 已废弃
systemPreferences.isDarkMode()
// 替换为
nativeTheme.shouldUseDarkColors

// 已废弃
systemPreferences.isInvertedColorScheme()
// 替换为
nativeTheme.shouldUseInvertedColorScheme

// 已废弃
systemPreferences.isHighContrastColorScheme()
// 替换为
nativeTheme.shouldUseHighContrastColors

Planned Breaking API Changes (7.0)

Deprecated: Atom.io Node Headers URL

这是在构建原生 node 模块时在 .npmrc 文件中指定为 disturl 的 url 或是 --dist-url 命令行标志. Both will be supported for the foreseeable future but it is recommended that you switch.

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

Replace with: https://electronjs.org/headers

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

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

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

API Changed: powerMonitor.querySystemIdleState is now powerMonitor.getSystemIdleState

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

API Changed: powerMonitor.querySystemIdleTime is now powerMonitor.getSystemIdleTime

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

API Changed: webFrame.setIsolatedWorldInfo replaces separate methods

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

Removed: marked property on getBlinkMemoryInfo

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

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

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

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

As an illustration, take a folder with this structure:

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

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

path/to/folder

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

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

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

API Changed: Callback-based versions of promisified APIs

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

These functions now only return Promises:

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

这些功能现在有两种形式,即同步和基于Promise的异步:

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

Planned Breaking API Changes (6.0)

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

// 不推荐
win.setMenu(null)
// 替换为
win.removeMenu()

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

// 不推荐
require('electron').screen
// 替换为
require('electron').remote.screen

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

// 不推荐
require('child_process')
// 替换为
require('electron').remote.require('child_process')

// 不推荐
require('fs')
// 替换为
require('electron').remote.require('fs')

// 不推荐
require('os')
// 替换为
require('electron').remote.require('os')

// 不推荐
require('path')
// 替换为
require('electron').remote.require('path')

Deprecated: powerMonitor.querySystemIdleState replaced with powerMonitor.getSystemIdleState

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

Deprecated: powerMonitor.querySystemIdleTime replaced with powerMonitor.getSystemIdleTime

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

Deprecated: app.enableMixedSandbox() is no longer needed

// Deprecated
app.enableMixedSandbox()

混合沙盒模式已默认启用。

Deprecated: Tray.setHighlightMode

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

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

Planned Breaking API Changes (5.0)

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

不推荐使用以下 webPreferences 选项默认值,以支持下面列出的新默认值。

属性不推荐使用的默认值新的默认值
contextIsolationfalsetrue
nodeIntegrationtruefalse
webviewTagnodeIntegration 未设置过则是 truefalse

如下: Re-enabling the webviewTag

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

Behavior Changed: nodeIntegration in child windows opened via nativeWindowOpen

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

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

Renderer process APIs webFrame.registerURLSchemeAsPrivileged and webFrame.registerURLSchemeAsBypassingCSP as well as browser process API protocol.registerStandardSchemes have been removed. 新的 API protocol.registerSchemeasviliged 已被添加,并用于注册具有必要权限的自定义 scheme。 自定义 scheme 需要在 app 触发 ready 事件之前注册。

Deprecated: webFrame.setIsolatedWorld* replaced with webFrame.setIsolatedWorldInfo

// 弃用
webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp)
webFrame.setIsolatedWorldHumanReadableName(worldId, name)
webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin)
// 替换为
webFrame.setIsolatedWorldInfo(
  worldId,
  {
    securityOrigin: 'some_origin',
    name: 'human_readable_name',
    csp: 'content_security_policy'
  })

API Changed: webFrame.setSpellCheckProvider now takes an asynchronous callback

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

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

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

webContents.getZoomLevel and webContents.getZoomFactor no longer take callback parameters, instead directly returning their number values.

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

以下列表包含了Electron4.0中重大的API更新

app.makeSingleInstance

// 已废弃
app.makeSingleInstance((argv, cwd) => {
  /* ... */
})
// 替换为
app.requestSingleInstanceLock()
app.on('second-instance', (event, argv, cwd) => {
  /* ... */
})

app.releaseSingleInstance

// 废弃
app.releaseSingleInstance()
// 替换为
app.releaseSingleInstanceLock()

app.getGPUInfo

app.getGPUInfo('complete')
// 现在的行为将与macOS下的`basic`设置一样
app.getGPUInfo('basic')

win_delay_load_hook

在为 Windows 构建本机模块时,将使 win_delay_load_hook 变量值 位于 binding.gyp 模块,必须为 true (这是默认值)。 如果这个钩子 不存在,那么本机模块将无法在 Windows 上加载,并出现错误 消息如 无法找到模块。 See the native module guide for more.

重大的API更新 (3.0)

以下包含了Electron 3.0中重大的API更新

app

// 弃用
app.getAppMemoryInfo()
// 替换为
app.getAppMetrics()

// 弃用
const metrics = app.getAppMetrics()
const { memory } = metrics[0] // 弃用的属性

BrowserWindow

// 已废弃
const optionsA = { webPreferences: { blinkFeatures: '' } }
const windowA = new BrowserWindow(optionsA)
// 替换为
const optionsB = { webPreferences: { enableBlinkFeatures: '' } }
const windowB = new BrowserWindow(optionsB)

// 已废弃
window.on('app-command', (e, cmd) => {
  if (cmd === 'media-play_pause') {
    // do something
  }
})
// 替换为
window.on('app-command', (e, cmd) => {
  if (cmd === 'media-play-pause') {
    // do something
  }
})

clipboard

// 过时的
clipboard.readRtf()
// 替换为
clipboard.readRTF()

// 过时的
clipboard.writeRtf()
// 替换为
clipboard.writeRTF()

// 过时的
clipboard.readHtml()
// 替换为
clipboard.readHTML()

// 过时的
clipboard.writeHtml()
//替换为
clipboard.writeHTML()

crashReporter

// 过时的
crashReporter.start({
  companyName: 'Crashly',
  submitURL: 'https://crash.server.com',
  autoSubmit: true
})
// 替换为
crashReporter.start({
  companyName: 'Crashly',
  submitURL: 'https://crash.server.com',
  uploadToServer: true
})

nativeImage

// 弃用
nativeImage.createFromBuffer(buffer, 1.0)
// 替换为
nativeImage.createFromBuffer(buffer, {
  scaleFactor: 1.0
})

process

// 弃用
const info = process.getProcessMemoryInfo()

screen

// 弃用
screen.getMenuBarHeight()
// 替换为
screen.getPrimaryDisplay().workArea

session

// 弃用
ses.setCertificateVerifyProc((hostname, certificate, callback) => {
  callback(true)
})
// 替换为
ses.setCertificateVerifyProc((request, callback) => {
  callback(0)
})

Tray

// 过时的
tray.setHighlightMode(true)
// 替换为
tray.setHighlightMode('on')

// 过时的
tray.setHighlightMode(false)
// 替换为
tray.setHighlightMode('off')

webContents

// 弃用
webContents.openDevTools({ detach: true })
// 替换为
webContents.openDevTools({ mode: 'detach' })

// 移除
webContents.setSize(options)
// 没有该API的替代

webFrame

// 弃用
webFrame.registerURLSchemeAsSecure('app')
// 替换为
protocol.registerStandardSchemes(['app'], { secure: true })

// 弃用
webFrame.registerURLSchemeAsPrivileged('app', { secure: true })
// 替换为
protocol.registerStandardSchemes(['app'], { secure: true })

<webview>

// 移除
webview.setAttribute('disableguestresize', '')
// 没有该API的替代

// 移除
webview.setAttribute('guestinstance', instanceId)
// 没有该API的替代

// 键盘监听器在webview标签中不再起效
webview.onkeydown = () => { /* handler */ }
webview.onkeyup = () => { /* handler */ }

Node Headers URL

这是在构建原生 node 模块时在 .npmrc 文件中指定为 disturl 的 url 或是 --dist-url 命令行标志.

过时的: https://atom.io/download/atom-shell

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

重大的API更新 (2.0)

以下包含了Electron 2.0中重大的API更新

BrowserWindow

// 已废弃
const optionsA = { titleBarStyle: 'hidden-inset' }
const windowA = new BrowserWindow(optionsA)
// 替换为
const optionsB = { titleBarStyle: 'hiddenInset' }
const windowB = new BrowserWindow(optionsB)

menu

// 移除
menu.popup(browserWindow, 100, 200, 2)
// 替换为
menu.popup(browserWindow, { x: 100, y: 200, positioningItem: 2 })

nativeImage

// 移除
nativeImage.toPng()
// 替换为
nativeImage.toPNG()

// 移除
nativeImage.toJpeg()
// 替换为
nativeImage.toJPEG()

process

  • process.versions.electronprocess.version.chrome 将成为只读属性, 以便与其他 process.versions 属性由Node设置。

webContents

// 移除
webContents.setZoomLevelLimits(1, 2)
// 替换为
webContents.setVisualZoomLevelLimits(1, 2)

webFrame

// 移除
webFrame.setZoomLevelLimits(1, 2)
// 替换为
webFrame.setVisualZoomLevelLimits(1, 2)

<webview>

// 移除
webview.setZoomLevelLimits(1, 2)
// 替换为
webview.setVisualZoomLevelLimits(1, 2)

重复的 ARM 资源

每个 Electron 发布版本包含两个相同的ARM版本,文件名略有不同,如electron-v1.7.3-linux-arm.zipelectron-v1.7.3-linux-armv7l.zip 添加包含v7l前缀的资源向用户明确其支持的ARM版本,并消除由未来armv6l 和 arm64 资源可能产生的歧义。

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

更多详细情况,查看 69867189