Критические изменения
Breaking changes will be documented here, and deprecation warnings added to JS code where possible, at least one major version before the change is made.
Note that breaking changes listed for future releases are always subject to change.
Типы критических изменений
В этом документе используется следующее соглашение для классификации критических изменений:
- Изменение API: API был изменен таким образом, что код, который не был обновлен, гарантировано бросит исключение.
- Изменение поведения: Поведение Electron было изменено, но не обязательно появление исключений.
- Изменено значение по-умолчанию: Код, работа которого зависит от старого значения по-умолчанию, может сломаться, не обязательно кидая исключение. Старое поведение можно восстановить, если явно указать значение.
- Устарело: API был помечен как устаревший. API продолжит функционировать, но будет появляться предупреждающее сообщение о том, что API будет удален в будущем релизе.
- Удалено: API или функция была удалена и больше не поддерживается Electron.
Критические изменения API (45.0)
Removed: Node.js module shims and Buffer, setImmediate, clearImmediate globals in sandboxed preload scripts
Sandboxed preload scripts (the default since Electron 20) and service worker preload scripts no longer have access to the events, timers and url Node.js module shims through require, and are no longer run with Buffer, setImmediate and clearImmediate in scope. These were browser polyfills bundled into every sandboxed renderer rather than the Node.js implementations. require in a sandboxed preload now only loads electron (and electron/renderer, electron/common); process and global are still provided.
Use the equivalent Web APIs instead, or bundle the polyfill you need into your preload script:
| Removed | Use instead |
|---|---|
require('events') / EventEmitter | EventTarget and Event, or bundle the events package |
require('timers'), setImmediate, clearImmediate | setTimeout / clearTimeout, queueMicrotask |
require('url') | URL, URLSearchParams |
Buffer | Uint8Array, TextEncoder / TextDecoder, atob / btoa, or bundle the buffer package |
ipcRenderer and the preload's process object keep their EventEmitter methods (on, once, off, emit, removeListener, removeAllListeners, ...). Preload scripts for renderers with sandbox: false are unaffected and continue to have the full Node.js environment.
Behavior Changed: ipcRenderer and process in sandboxed preload scripts use a native EventEmitter
In sandboxed preload scripts and service worker preload scripts, ipcRenderer, webFrame and the preload's process object now inherit from an EventEmitter implemented natively by Electron instead of one from a bundled copy of the events npm package. It provides the same instance API as before (on, once, off, emit, addListener, removeListener, removeAllListeners, prependListener, prependOnceListener, listeners, rawListeners, listenerCount, eventNames, setMaxListeners, getMaxListeners, the newListener / removeListener events and the max-listener warning) with the same behavior. The static helpers that were only reachable through require('events') (once, listenerCount, init) are not provided.
Behavior Changed: workers created by subframes need nodeIntegrationInSubFrames for Node.js integration
With nodeIntegrationInWorker: true, a Worker created from an <iframe> in the same process as the main frame used to get Node.js integration even though the iframe itself had none. Workers now only get Node.js integration when the frame that creates them has it: the main frame, or any frame when nodeIntegrationInSubFrames is enabled.
This change was also backported to Electron 44.3.0, 43.7.0 and 42.11.3.
Behavior Changed: preload scripts only run in DevTools extension frames hosted by DevTools
A chrome-extension:// document used to receive the window's preload script (and session preload scripts) wherever it was embedded. It now only does so when it is a top-level frame or is hosted inside the DevTools front-end (a devtools_page or panel); an extension frame embedded in an ordinary page is treated like any other subframe and follows nodeIntegrationInSubFrames.
This change was also backported to Electron 44.3.0, 43.7.0 and 42.11.3.
Behavior Changed: getUserMedia with chromeMediaSource: 'desktop' rejects WebContents source ids
The legacy chromeMediaSource: 'desktop' constraint now only accepts screen and window source ids from desktopCapturer.getSources. Passing a WebContents source id there now fails with an "Invalid state" error. To capture a WebContents, use chromeMediaSource: 'tab' with an id from webContents.getMediaSourceId(), or use ses.setDisplayMediaRequestHandler.
// Main process
const sourceId = targetContents.getMediaSourceId(requestingContents)
// Renderer process of requestingContents
const stream = await navigator.mediaDevices.getUserMedia({
video: {
mandatory: {
chromeMediaSource: 'tab',
chromeMediaSourceId: sourceId
}
}
})
This change was also backported to Electron 44.3.0, 43.7.0 and 42.11.3.
Удален: contentTracing.enableHeapProfiling()
The experimental contentTracing.enableHeapProfiling() API has been removed. Chromium removed the memlog implementation that backed this API and replaced it with a Perfetto heap-profiling data source. Pass a nativeHeapProfiling option to contentTracing.startRecording() to enable heap profiling for the duration of a trace. Like all recordings, heap-enabled recordings use the Perfetto protobuf format.
The old options map to the new ones as follows:
samplingRateis nownativeHeapProfiling.samplingInterval.modehas no direct equivalent. Every traced process is profiled; useincluded_process_idsin aTraceConfigto limit which processes are traced.stackModehas no equivalent.
await contentTracing.startRecording({
nativeHeapProfiling: {
samplingInterval: 128 * 1024
}
})
Behavior Changed: contentTracing recordings use the Perfetto protobuf format
contentTracing.stopRecording() used to write traces in the legacy JSON trace format. It now always writes the Perfetto protobuf format, and the JSON format is no longer available. Open recordings in the Perfetto UI, or query them with Perfetto's Trace Processor. If you still need the legacy JSON format, Perfetto's traceconv tool can convert a recording to it.
Behavior Changed: screen capture requests are reported as display-capture in setPermissionRequestHandler
Requests to capture the screen, a window or a tab -- made through navigator.mediaDevices.getDisplayMedia() or through getUserMedia() with the chromeMediaSource / chromeMediaSourceId constraints used with desktopCapturer -- are now passed to session.setPermissionRequestHandler with the documented display-capture permission. Previously they were reported as media with an empty details.mediaTypes array, indistinguishable from a camera or microphone request other than by that empty array. media is now only used for camera and microphone devices.
Applications with a permission request handler that grants media and denies everything else must also grant display-capture to keep screen sharing working:
session.defaultSession.setPermissionRequestHandler((webContents, permission, callback, details) => {
if (permission === 'media' || permission === 'display-capture') {
return callback(true)
}
callback(false)
})
For display-capture requests, details.mediaTypes now lists video and/or audio to indicate whether display video and/or display audio was requested. The setDisplayMediaRequestHandler flow for getDisplayMedia() is unchanged and still runs after the permission request has been granted.
The display-capture Permissions-Policy is now also applied to getUserMedia() calls that use the chromeMediaSource constraints, matching getDisplayMedia(). Its default allowlist is self, so a cross-origin <iframe> that captures the screen this way now needs allow="display-capture" on the iframe element.
Default Changed: document.requestStorageAccessFor is disabled
Chromium has disabled document.requestStorageAccessFor by default ahead of its removal. The API can temporarily be restored with the enableBlinkFeatures web preference set to RequestStorageAccessFor. See Chromium's intent to remove discussion for more information.
Behavior Changed: file descriptors for files inside ASAR archives are only usable through fs
fs.open, fs.openSync and fs.promises.open on a file inside an ASAR archive used to extract the file to a temporary copy and return a descriptor for that copy. They now return a descriptor that only identifies the entry to Node's fs module, which reads directly out of the archive with no temporary file (fs.read, fs.readv, fs.fstat, fs.readFile(fd), fs.createReadStream and the FileHandle methods). The descriptor itself is not backed by the file's contents: code that reads the raw descriptor (a native addon, child_process stdio, net.Socket({ fd }), http2stream.respondWithFile() / respondWithFD(), a FileHandle transferred to a worker, ...) fails with EBADF and is not supported. Opening a file inside an archive with a flag that allows writing (w, a, r+, ...) now fails with EACCES instead of silently writing to the temporary copy, and fs.fchmod, fs.fchown and fs.futimes on these descriptors fail with EACCES.
fs.stat on a symbolic link inside an archive now follows the link like it does on a real filesystem (fs.lstat still describes the link itself).
Behavior Changed: window.open() children of unsandboxed windows get their own sandboxed process
A window.open() child normally shares its opener's renderer process, and the OS sandbox of a renderer process is fixed when it launches. Previously a child opened from an unsandboxed (e.g. nodeIntegration: true) window silently ran in that unsandboxed process even though webContents.getLastWebPreferences() reported sandbox: true for it.
Now the child's own web preferences decide the sandbox state, and when that state differs from the opener's process the child is created in a new process with no opener relationship: window.open() returns null in the opener and window.opener is null in the child, matching the behavior of window.open(url, '_blank', 'noopener'). A warning is logged to the opener's console when this happens.
Child windows default to sandboxed, so a child opened from an unsandboxed window is now isolated in its own sandboxed process by default. To restore the previous behavior of sharing the opener's unsandboxed process (and the scriptable window.opener / returned WindowProxy that comes with it), opt in explicitly from webContents.setWindowOpenHandler:
win.webContents.setWindowOpenHandler(() => ({
action: 'allow',
overrideBrowserWindowOptions: {
webPreferences: {
// Match the (unsandboxed) opener so the child shares its process.
sandbox: false
}
}
}))
Setting nodeIntegration: true in the override also makes the child unsandboxed and has the same effect.
Deprecated: safeStorage.isEncryptionAvailable(), safeStorage.encryptString() and safeStorage.decryptString()
The synchronous safeStorage methods are deprecated and will be removed in Electron 46, following Chromium's removal of the synchronous OSCrypt backend they are built on. Use the asynchronous methods instead, which use the same per-platform key stores. Data encrypted with safeStorage.encryptString() can be decrypted with safeStorage.decryptStringAsync().
// Deprecated
if (safeStorage.isEncryptionAvailable()) {
const encrypted = safeStorage.encryptString('secret')
const decrypted = safeStorage.decryptString(encrypted)
}
// Replace with
if (await safeStorage.isAsyncEncryptionAvailable()) {
const encrypted = await safeStorage.encryptStringAsync('secret')
const { result: decrypted } = await safeStorage.decryptStringAsync(encrypted)
}
Критические изменения API (44.0)
Behavior Changed: webContents may be null in select-client-certificate
The app 'select-client-certificate' event is now also emitted for requests made via the net module and for utility processes created with respondToAuthRequestsFromMainProcess: true. For these requests the webContents argument is null. Previously the event was only emitted for requests originating from a WebContents and the argument was always non-null.
As with WebContents requests, when the event is not handled (or event.preventDefault() is not called) Electron uses the first matching client certificate from the platform certificate store. Previously net requests to a server that requested a client certificate failed with ERR_SSL_CLIENT_AUTH_CERT_NEEDED. To opt out, handle the event and call callback() with no argument to continue without a client certificate.
// Before
app.on('select-client-certificate', (event, webContents, url, list, callback) => {
console.log(webContents.id)
})
// After
app.on('select-client-certificate', (event, webContents, url, list, callback) => {
if (webContents) console.log(webContents.id)
})
Removed: macOS 12 support
macOS 12 (Monterey) is no longer supported by Chromium.
Older versions of Electron will continue to run on Monterey, but macOS 13 (Ventura) or later will be required to run Electron v44.0.0 and higher.
Behavior Changed: ANGLE is statically linked on all platforms
ANGLE is now statically linked into the Electron binary on all platforms, matching upstream Chromium. The libEGL.(so|dylib|dll) and libGLESv2.(so|dylib|dll) libraries are no longer shipped in the distribution.
Apps that replaced or managed their own ANGLE versions by swapping out these libraries can no longer do so. Additionally, because ANGLE is now part of the Electron binary, it is loaded into every process rather than only the GPU process, which may surface regressions in unusual configurations.
Behavior Changed: net.request rejects frame destinations without navigate mode
net.request now rejects requests where Sec-Fetch-Dest is document, frame, iframe, or fencedframe unless Sec-Fetch-Mode is also set to navigate. This matches Chromium's enforcement that frame-type request destinations must be navigations.
Apps that explicitly set one of these Sec-Fetch-Dest values on a net.request must also set Sec-Fetch-Mode to navigate.
Removed: Unity desktop environment support on Linux
Unity has not been the default desktop environment in Ubuntu LTS since version 16.04, which is not supported by current versions of Electron. The deprecation does not prevent Electron from running on Unity if it is installed in a newer distribution, but it will no longer offer unique functionality. In general, Electron supports modern Freedesktop standards on Linux rather than APIs which only work in specific environments.
One API has been removed: app.isUnityRunning(). Some Unity-specific APIs no longer function on Linux, but remain supported on other platforms:
app.setBadgeCount(count)andapp.badgeCountmacOSBaseWindow.setProgressBar(progress)andBrowserWindow.setProgressBar(progress)Windows macOS.
Removed: Windows 32-bit (ia32) and Linux 32-bit ARM (armv7l) support
Electron no longer publishes prebuilt binaries for 32-bit platforms: Windows x86 (win32-ia32) and Linux ARM (linux-armv7l). All related release artifacts (chromedriver, mksnapshot, ffmpeg, and the Windows x86 node.lib on the Electron headers CDN) are no longer published either.
Older versions of Electron will continue to support these platforms, but Electron v44.0.0 and higher will only be published for 64-bit platforms.
Once the v43 series reaches end of life in January 2027, these 32-bit platforms will no longer be supported.
Removed: clipboard module is no longer available in the renderer process
The clipboard module is no longer exposed to renderer processes. It was previously deprecated and is now removed in line with RFC 0019 to close the security risk of granting non-sandboxed renderers direct clipboard access.
Renderers should use the navigator.clipboard API to safely work with the system clipboard. If more advanced usage is necessary, expose the necessary helpers from a preload script using the contextBridge API. When using contextBridge care must be taken to ensure that the clipboard API is not exposed to untrusted content.
API Changed: clipboard module rearchitected to align with the W3C Clipboard API
The clipboard module has been rearchitected to align with the W3C Clipboard API. The four read/write methods now all return Promises, matching navigator.clipboard:
clipboard.read()returnsPromise<ClipboardItem[]>. Each item exposes atypesarray andgetType(type) → Promise<Blob>for lazy retrieval — matching the W3CClipboardIteminstance shape.getType('electron application/bookmark')is the one exception: it resolves to a{ title, url }object instead of aBlob.clipboard.write(items)returnsPromise<void>and accepts an array ofClipboardIteminstances constructed vianew ClipboardItem({ [mime]: payload })— modeled after the W3CClipboardItem(items)constructor. Each payload value isBlob | string | Object(astringis committed as UTF-8 and aBlob's bytes are committed verbatim). Theelectron application/bookmarkcustom format instead takes a{ title, url }object. All entries in a singlewrite()call are committed atomically.clipboard.readText()returnsPromise<string>.clipboard.writeText(text)returnsPromise<void>.- The
text/uri-listMIME type maps to the operating system's native file-reference format (CF_HDROPon Windows,NSFilenamesPboardTypeon macOS,text/uri-liston Linux) rather than a generic text payload. Its payload is an RFC 2483file://URI list, soclipboard.read()/clipboard.write()can read and write files copied to and from native applications. SeeClipboardItemfor details.
clipboard.has(mimetype) now returns Promise<boolean> because the underlying Chromium clipboard API is asynchronous. Additionally, instead of taking a format, clipboard.has() accepts a MIME type. To check for a raw format, eg public/utf8-plain-text, use the electron application/osclipboard custom format (electron application/osclipboard;format="public/utf8-plain-text").
The narrowly-scoped helpers (availableFormats, readBookmark, writeBookmark, readBuffer, writeBuffer, readFindText, writeFindText, readHTML, writeHTML, readImage, writeImage, readRTF, writeRTF) and the optional type parameter accepted by clipboard.clear, clipboard.has, clipboard.readText, and clipboard.writeText have been removed. The Linux selection clipboard is now reached through a new clipboard.selection sub-namespace.
| Old API | New API |
|---|---|
clipboard.availableFormats([type]) | clipboard.read() - iterate through ClipboardItem array and collect types |
clipboard.clear() | clipboard.clear() (no type parameter) |
clipboard.clear('selection') Linux | clipboard.selection.clear() |
clipboard.has(format) | clipboard.has(mimetype) now returns Promise<boolean> |
clipboard.has(format, 'selection') Linux | clipboard.selection.has(mimetype) (returns Promise<boolean>) |
clipboard.read() | clipboard.read() now returns Promise<ClipboardItem[]> |
clipboard.read('selection') Linux | clipboard.selection.read() (returns Promise<ClipboardItem[]>) |
clipboard.readBookmark() | clipboard.read() with electron application/bookmark custom format |
clipboard.readBuffer(format) | clipboard.read() with electron application/osclipboard;format="..." custom format |
clipboard.readBuffer('selection') Linux | clipboard.selection.read() with electron application/osclipboard;format="..." custom format |
clipboard.readFindText() macOS | clipboard.read() with electron application/findtext custom format |
clipboard.readHTML([type]) | clipboard.read() with text/html MIME type |
clipboard.readImage([type]) | clipboard.read() with image/* MIME type |
clipboard.readRTF([type]) | clipboard.read() with text/rtf MIME type |
clipboard.readText() | clipboard.readText() now returns Promise<string> |
clipboard.readText('selection') Linux | clipboard.selection.readText() (returns Promise<string>) |
clipboard.write(data) | clipboard.write([new ClipboardItem({ [mime]: Blob / string })]) — accepts an array of ClipboardItem objects (each with a MIME-keyed data record) and returns Promise<void> |
clipboard.write(data, 'selection') Linux | clipboard.selection.write([new ClipboardItem({ [mime]: Blob / string })]) (returns Promise<void>) |
clipboard.writeBookmark(title, url[, type]) | clipboard.write() with electron application/bookmark custom format |
clipboard.writeBuffer(format, buffer[, type]) | clipboard.write() with electron application/osclipboard;format="..." custom format |
clipboard.writeBuffer(format, buffer, 'selection') Linux | clipboard.selection.write() with electron application/osclipboard;format="..." custom format |
clipboard.writeFindText(text) macOS | clipboard.write() with electron application/findtext custom format |
clipboard.writeHTML(markup[, type]) | clipboard.write() with text/html MIME type |
clipboard.writeImage(image[, type]) | clipboard.write() with image/* MIME type |
clipboard.writeRTF(text[, type]) | clipboard.write() with text/rtf MIME type |
clipboard.writeText(text) | clipboard.writeText(text) now returns Promise<void> |
clipboard.writeText(text, 'selection') Linux | clipboard.selection.writeText(text) (returns Promise<void>) |
Example migration code
const { clipboard, ClipboardItem } = require('electron')
function getClipboardToUse(clipboardType) {
if (clipboardType === 'selection') {
return clipboard.selection
} else {
return clipboard
}
}
async function readClipboard(format, clipboardType) {
const clipboardToUse = getClipboardToUse(clipboardType)
const clipboardItems = await clipboardToUse.read()
const foundItem = clipboardItems.find((clipboardItem) => {
return clipboardItem.types.includes(format)
})
if (foundItem) {
// getType() resolves to a Blob; read it back as text.
const blob = await foundItem.getType(format)
return blob.text()
}
}
async function writeClipboard(format, text, clipboardType) {
const clipboardToUse = getClipboardToUse(clipboardType)
return clipboardToUse.write([
new ClipboardItem({
[format]: text
})
])
}
async function readBuffer(format, clipboardType) {
const clipboardToUse = getClipboardToUse(clipboardType)
const clipboardItems = await clipboardToUse.read()
const foundItem = clipboardItems.find((clipboardItem) => {
return clipboardItem.types.includes(format)
})
if (foundItem) {
// getType() resolves to a Blob; convert it to a Buffer.
const blob = await foundItem.getType(format)
return Buffer.from(await blob.arrayBuffer())
}
}
async function writeBuffer(format, buffer, clipboardType) {
const clipboardToUse = getClipboardToUse(clipboardType)
return clipboardToUse.write([
new ClipboardItem({
[format]: new Blob([buffer])
})
])
}
async function availableFormats(clipboardType) {
const clipboardToUse = getClipboardToUse(clipboardType)
const clipboardItems = await clipboardToUse.read()
const clipboardFormats = []
for (const clipboardItem of clipboardItems) {
for (const type of clipboardItem.types) {
if (!clipboardFormats.includes(type)) {
clipboardFormats.push(type)
}
}
}
return clipboardFormats
}
async function has(format, clipboardType, isRawFormat) {
const clipboardToUse = getClipboardToUse(clipboardType)
let mimeType = format
if (isRawFormat) {
mimeType = `electron application/osclipboard;format="${format}"`
}
return clipboardToUse.has(mimeType)
}
const BOOKMARK_MIME_TYPE = 'electron application/bookmark'
async function readBookmark(clipboardType) {
const clipboardToUse = getClipboardToUse(clipboardType)
const clipboardItems = await clipboardToUse.read()
const foundItem = clipboardItems.find((clipboardItem) => {
return clipboardItem.types.includes(BOOKMARK_MIME_TYPE)
})
if (foundItem) {
// getType('electron application/bookmark') resolves to a
// { title, url } object rather than a Buffer.
return foundItem.getType(BOOKMARK_MIME_TYPE)
}
}
async function writeBookmark(title, url, clipboardType) {
const clipboardToUse = getClipboardToUse(clipboardType)
return clipboardToUse.write([
new ClipboardItem({
[BOOKMARK_MIME_TYPE]: { title, url }
})
])
}
const FIND_TEXT_MIME_TYPE = 'electron application/findtext'
async function readFindText() {
return readClipboard(FIND_TEXT_MIME_TYPE)
}
async function writeFindText(text) {
return writeClipboard(FIND_TEXT_MIME_TYPE, text)
}
const HTML_MIME_TYPE = 'text/html'
async function readHTML(clipboardType) {
return readClipboard(HTML_MIME_TYPE, clipboardType)
}
async function writeHTML(markup, clipboardType) {
return writeClipboard(HTML_MIME_TYPE, markup, clipboardType)
}
const PNG_MIME_TYPE = 'image/png'
const JPEG_MIME_TYPE = 'image/jpeg'
async function readImage(clipboardType) {
const clipboardToUse = getClipboardToUse(clipboardType)
const clipboardItems = await clipboardToUse.read()
// Look for PNG first
let foundItem = clipboardItems.find((clipboardItem) => {
return clipboardItem.types.includes(PNG_MIME_TYPE)
})
if (!foundItem) {
foundItem = clipboardItems.find((clipboardItem) => {
return clipboardItem.types.includes(JPEG_MIME_TYPE)
})
}
if (foundItem) {
const mimeType = foundItem.types.includes(PNG_MIME_TYPE) ? PNG_MIME_TYPE : JPEG_MIME_TYPE
// getType() resolves to a Blob; convert it to a Buffer for nativeImage.
const blob = await foundItem.getType(mimeType)
const buffer = Buffer.from(await blob.arrayBuffer())
return nativeImage.createFromBuffer(buffer)
}
}
async function writeImage(image, clipboardType) {
const clipboardToUse = getClipboardToUse(clipboardType)
return clipboardToUse.write([
new ClipboardItem({
'image/png': new Blob([image.toPNG()], { type: 'image/png' })
})
])
}
const RTF_MIME_TYPE = 'text/rtf'
async function readRTF(clipboardType) {
return readClipboard(RTF_MIME_TYPE, clipboardType)
}
async function writeRTF(text, clipboardType) {
return writeClipboard(RTF_MIME_TYPE, text, clipboardType)
}
Removed: Pre-macOS 13 login item attributes
Electron 44 removes the option openAsHidden from app.setLoginItemSettings() and the fields openAsHidden, wasOpenedAsHidden and restoreState from the return value of app.getLoginItemSettings().
These only worked on macOS 12 and below. Support for macOS 12 has been dropped.
Критические изменения API (43.0)
Behavior Changed: Rounded corners on Linux
Frameless windows default to rounded corners on Linux if the desktop environment supports client-side decorations. This can be configured using the existing roundedCorners option on BrowserWindow, which is now supported on Linux and defaults to true on all platforms.
Behavior Changed: WCO respects the native title bar layout on Linux
Frameless windows with Window Controls Overlay (WCO) now adopt the native title bar layout and user settings on Linux. For example, controls will appear on the left side of the frame on RTL systems, and only the close button will be visible by default on GNOME. Depending on the user's desktop environment and configuration, buttons can appear on the left or right side of the frame (or both). To account for all possibilities, use the CSS variables env(titlebar-area-x, 0px) and env(titlebar-area-width, 100%) to constrain your app's title bar content to a safe area.
Behavior Changed: NativeImage.toBitmap() now normalizes color space
NativeImage.toBitmap() (and its deprecated alias NativeImage.getBitmap()) now normalizes pixel data to sRGB by default. Previously, raw pixel data was returned without color space conversion, which meant pixel values from images with different embedded color profiles (e.g., Display P3 on macOS) could differ for the same visual color.
To preserve the previous behavior, pass the image's original color space in the colorSpace option. You can also pass colorSpace to convert to any other specific color space:
const image = nativeImage.createFromPath('photo.png')
// New default: normalized to sRGB
const srgbBitmap = image.toBitmap()
// Convert to Display P3
const p3Bitmap = image.toBitmap({
colorSpace: {
primaries: 'p3',
transfer: 'srgb',
matrix: 'rgb',
range: 'full'
}
})
Behavior Changed: chrome.scripting CSS injection matches more fallback frames
Extensions using chrome.scripting.insertCSS() or chrome.scripting.removeCSS() now follow Chrome's behavior when Electron cannot match a frame's URL directly, such as with about:blank or data: frames. If the extension has access to the page that created the frame, CSS may now be inserted into or removed from those fallback frames as well.
Apps or extensions that relied on Electron skipping those frames should narrow their injection target, frame IDs, or match patterns.
Behavior Changed: Dialog methods default to Downloads directory
The defaultPath option for the following methods now defaults to the user's Downloads folder (or their home directory if Downloads doesn't exist) when not explicitly provided:
dialog.showOpenDialogdialog.showOpenDialogSyncdialog.showSaveDialogdialog.showSaveDialogSync
Previously, when no defaultPath was provided, the underlying OS file dialog would determine the initial directory — typically remembering the last directory the user navigated to, or falling back to an OS-specific default. Now, Electron explicitly sets the initial directory to Downloads, which also means the OS will no longer track and restore the last-used directory between dialog invocations.
To preserve the old behavior, you can track the last-used directory yourself and pass it as defaultPath:
const path = require('node:path')
let lastUsedPath
const result = await dialog.showOpenDialog({
defaultPath: lastUsedPath
})
if (!result.canceled && result.filePaths.length > 0) {
lastUsedPath = path.dirname(result.filePaths[0])
}
Removed: showHiddenFiles in Dialogs on Linux
The showHiddenFiles property is no longer supported on Linux. It continues to work on macOS and Windows. GTK intends for this feature to be a user choice rather than an app choice, and has removed the API to do this programmatically.
Критические изменения API (42.0)
Behavior Changed: macOS notifications now use UNNotification API
Electron has migrated from the deprecated NSUserNotification API to the UNNotification API on macOS. The new API requires that an application be code-signed in order for notifications to be displayed. If an application is not code-signed, notifications will emit a failed event on the Notification object.
Behavior Changed: Offscreen rendering will use 1.0 as default device scale factor.
Previously, OSR used the primary display's device scale factor for rendering, which made the output frame size vary across users. Developers had to manually calculate the correct size using screen.getPrimaryDisplay().scaleFactor. We now provide an optional property webPreferences.offscreen.deviceScaleFactor to specify a custom value when creating an OSR window. At first, if the property is not set, it defaults to the primary display's scale factor (preserving the old behavior). Starting from Electron 42, the default will change to a constant value of 1.0 for more consistent output sizes.
Behavior Changed: electron no longer downloads itself via postinstall script
Previously, the electron npm package would download the Electron binary from the repository's GitHub Releases in the package's postinstall script.
With recent supply chain security attacks against the npm ecosystem with postinstall scripts as a common attack vector, Electron will now download itself dynamically the first time that its main bin script is run (e.g. via npx electron). With this change, you can now use Electron with the npm --ignore-scripts flag. See RFC #22 for more context.
# won't install binary to `node_modules/electron`
npm install electron --save-dev --ignore-scripts
# will download the binary on demand before starting electron process
npx electron .
# subsequent runs will used the binary downloaded from the first run
npx electron .
If you need to download the Electron binary on-demand, you can now call the install-electron script, which contains the exact same code from the former postinstall script.
npm install electron --save-dev --ignore-scripts
npx install-electron --no
If you need to test changes across platforms or architectures, you should now use the ELECTRON_INSTALL_ARCH and ELECTRON_INSTALL_PLATFORM environment variables.
# before: pass npm config flag on install command
npm install --platform=mas electron --save-dev
# after: add env var when you first run the Electron command
npm install electron --save-dev
ELECTRON_INSTALL_PLATFORM=mas npx electron . --no
This also means the ELECTRON_SKIP_BINARY_DOWNLOAD environment variable is no longer supported, as its primary purpose was to prevent the postinstall script from running.
Removed: quotas object from Session.clearStorageData(options)
When calling Session.clearStorageData(options), the options.quotas object is no longer supported because it has been removed from upstream Chromium.
Deprecated: Passing only an array hslShift to nativeImage.createFromNamedImage()
Passing only an array hslShift to nativeImage.createFromNamedImage() is deprecated. You should now pass an options object with an hslShift property instead:
// Deprecated
nativeImage.createFromNamedImage(imageName, [0, 1, -1])
// Replace with
nativeImage.createFromNamedImage(imageName, {
hslShift: [0, 1, -1]
})
Критические изменения API (41.0)
Behavior Changed: PDFs no longer create a separate WebContents
Previously, PDF resources created a separate guest WebContents for rendering. Now, PDFs are rendered within the same WebContents instead. If you have code to detect PDF resources, use the frame tree instead of WebContents.
Under the hood, Chromium enabled a feature that changes PDFs to use out-of-process iframes (OOPIFs) instead of the MimeHandlerViewGuest extension.
Behavior Changed: Updated Cookie Change Cause in the Cookie 'changed' Event
We have updated the cookie change cause in the cookie 'changed' event. When a new cookie is set, the change cause is inserted. When a cookie is deleted, the change cause remains explicit. When the cookie being set is identical to an existing one (same name, domain, path, and value, with no actual changes), the change cause is inserted-no-change-overwrite. When the value of the cookie being set remains unchanged but some of its attributes are updated, such as the expiration attribute, the change cause will be inserted-no-value-change-overwrite.
Deprecated: showHiddenFiles in Dialogs on Linux
This property will still be honored on macOS and Windows, but support on Linux will be removed in a future version of Electron. GTK intends for this to be a user choice rather than an app choice and has removed the API to do this programmatically.
Критические изменения API (40.0)
Deprecated: clipboard API access from renderer processes
Using the clipboard API directly in the renderer process is deprecated. If you want to call this API from a renderer process, place the API call in your preload script and expose it using the contextBridge API.
Behavior Changed: MacOS dSYM files now compressed with tar.xz
Debug symbols for MacOS (dSYM) now use xz compression in order to handle larger file sizes. dsym.zip files are now dsym.tar.xz files. End users using debug symbols may need to update their zip utilities.
Критические изменения API (39.0)
Deprecated: --host-rules command line switch
Chromium is deprecating the --host-rules switch.
You should use --host-resolver-rules instead.
Behavior Changed: window.open popups are always resizable
Per current WHATWG spec, the window.open API will now always create a resizable popup window.
To restore previous behavior:
webContents.setWindowOpenHandler((details) => {
return {
action: 'allow',
overrideBrowserWindowOptions: {
resizable: details.features.includes('resizable=yes')
}
}
})
Behavior Changed: NSAudioCaptureUsageDescription should be included in your app's Info.plist file to use desktopCapturer (🍏 macOS ≥14.2)
Per Chromium update which enables Apple's newer CoreAudio Tap API by default, you now must have NSAudioCaptureUsageDescription defined in your Info.plist to use desktopCapturer.
Electron's desktopCapturer will create a dead audio stream if the new permission is absent however no errors or warnings will occur. This is partially a side-effect of Chromium not falling back to the older Screen & System Audio Recording permissions system if the new system fails.
To restore previous behavior (Electron 39 through 44 only; the flag was removed upstream in Electron 45 and no longer has any effect):
// main.js (right beneath your require/import statements)
app.commandLine.appendSwitch('disable-features', 'MacCatapLoopbackAudioForScreenShare')
Behavior Changed: shared texture OSR paint event data structure
When using shared texture offscreen rendering feature, the paint event now emits a more structured object. It moves the sharedTextureHandle, planes, modifier into a unified handle property. See the OffscreenSharedTexture API structure for more details.
Критические изменения API (38.0)
Removed: ELECTRON_OZONE_PLATFORM_HINT environment variable
The default value of the --ozone-platform flag changed to auto.
Electron now defaults to running as a native Wayland app when launched in a Wayland session (when XDG_SESSION_TYPE=wayland). Users can force XWayland by passing --ozone-platform=x11.
Removed: ORIGINAL_XDG_CURRENT_DESKTOP environment variable
Previously, Electron changed the value of XDG_CURRENT_DESKTOP internally to Unity, and stored the original name of the desktop session in a separate variable. XDG_CURRENT_DESKTOP is no longer overridden and now reflects the actual desktop environment.
Removed: macOS 11 support
macOS 11 (Big Sur) is no longer supported by Chromium.
Older versions of Electron will continue to run on Big Sur, but macOS 12 (Monterey) or later will be required to run Electron v38.0.0 and higher.
Removed: plugin-crashed event
The plugin-crashed event has been removed from webContents.
Deprecated: webFrame.routingId property
The routingId property will be removed from webFrame objects.
You should use webFrame.frameToken instead.
Устарело: webFrame.findFrameByRoutingId(routingId)
The webFrame.findFrameByRoutingId(routingId) function will be removed.
You should use webFrame.findFrameByToken(frameToken) instead.
Критические изменения API (37.0)
Utility Process unhandled rejection behavior change
Utility Processes will now warn with an error message when an unhandled rejection occurs instead of crashing the process.
To restore the previous behavior, you can use:
process.on('unhandledRejection', () => {
process.exit(1)
})
Behavior Changed: process.exit() kills utility process synchronously
Calling process.exit() in a utility process will now kill the utility process synchronously. This brings the behavior of process.exit() in line with Node.js behavior.
Please refer to the Node.js docs and PR #45690 to understand the potential implications of that, e.g., when calling console.log() before process.exit().
Behavior Changed: WebUSB and WebSerial Blocklist Support
WebUSB and Web Serial now support the WebUSB Blocklist and Web Serial Blocklist used by Chromium and outlined in their respective specifications.
To disable these, users can pass disable-usb-blocklist and disable-serial-blocklist as command line flags.
Removed: null value for session property in ProtocolResponse
This deprecated feature has been removed.
Previously, setting the ProtocolResponse.session property to null would create a random independent session. This is no longer supported.
Using single-purpose sessions here is discouraged due to overhead costs; however, old code that needs to preserve this behavior can emulate it by creating a random session with session.fromPartition(some_random_string) and then using it in ProtocolResponse.session.
Behavior Changed: BrowserWindow.IsVisibleOnAllWorkspaces() on Linux
BrowserWindow.IsVisibleOnAllWorkspaces() will now return false on Linux if the window is not currently visible.
Критические изменения API (36.0)
Behavior Changes: app.commandLine
app.commandLine will convert upper-cases switches and arguments to lowercase.
app.commandLine was only meant to handle chromium switches (which aren't case-sensitive) and switches passed via app.commandLine will not be passed down to any of the child processes.
If you were using app.commandLine to control the behavior of the main process, you should do this via process.argv.
Устарело: NativeImage.getBitmap()
NativeImage.toBitmap() returns a newly-allocated copy of the bitmap. NativeImage.getBitmap() was originally an alternative function that returned the original instead of a copy. This changed when sandboxing was introduced, so both return a copy and are functionally equivalent.
Client code should call NativeImage.toBitmap() instead:
// Deprecated
bitmap = image.getBitmap()
// Use this instead
bitmap = image.toBitmap()
Removed: isDefault and status properties on PrinterInfo
These properties have been removed from the PrinterInfo Object because they have been removed from upstream Chromium.
Removed: quota type syncable in Session.clearStorageData(options)
When calling Session.clearStorageData(options), the options.quota type syncable is no longer supported because it has been removed from upstream Chromium.
Deprecated: null value for session property in ProtocolResponse
Previously, setting the ProtocolResponse.session property to null would create a random independent session. This is no longer supported.
Using single-purpose sessions here is discouraged due to overhead costs; however, old code that needs to preserve this behavior can emulate it by creating a random session with session.fromPartition(some_random_string) and then using it in ProtocolResponse.session.
Deprecated: quota property in Session.clearStorageData(options)
When calling Session.clearStorageData(options), the options.quota property is deprecated. Since the syncable type was removed, there is only one type left -- 'temporary' -- so specifying it is unnecessary.
Deprecated: Extension methods and events on session
session.loadExtension, session.removeExtension, session.getExtension, session.getAllExtensions, 'extension-loaded' event, 'extension-unloaded' event, and 'extension-ready' events have all moved to the new session.extensions class.
Удален: systemPreferences.isAeroGlassEnabled()
The systemPreferences.isAeroGlassEnabled() function has been removed without replacement. It has been always returning true since Electron 23, which only supports Windows 10+, where DWM composition can no longer be disabled.
Changed: GTK 4 is default when running GNOME
After an upstream change, GTK 4 is now the default when running GNOME.
In rare cases, this may cause some applications or configurations to error with the following message:
Gtk-ERROR **: 11:30:38.382: GTK 2/3 symbols detected. Using GTK 2/3 and GTK 4 in the same process is not supported
Affected users can work around this by specifying the gtk-version command-line flag:
$ electron --gtk-version=3 # или --gtk-version=2
The same can be done with the app.commandLine.appendSwitch function.
Критические изменения API (35.0)
Behavior Changed: Dialog API's defaultPath option on Linux
On Linux, the required portal version for file dialogs has been reverted to 3 from 4. Using the defaultPath option of the Dialog API is not supported when using portal file chooser dialogs unless the portal backend is version 4 or higher. The --xdg-portal-required-version command-line switch can be used to force a required version for your application. See #44426 for more details.
Deprecated: getFromVersionID on session.serviceWorkers
The session.serviceWorkers.fromVersionID(versionId) API has been deprecated in favor of session.serviceWorkers.getInfoFromVersionID(versionId). This was changed to make it more clear which object is returned with the introduction of the session.serviceWorkers.getWorkerFromVersionID(versionId) API.
// Deprecated
session.serviceWorkers.fromVersionID(versionId)
// Replace with
session.serviceWorkers.getInfoFromVersionID(versionId)
Deprecated: setPreloads, getPreloads on Session
registerPreloadScript, unregisterPreloadScript, and getPreloadScripts are introduced as a replacement for the deprecated methods. These new APIs allow third-party libraries to register preload scripts without replacing existing scripts. Also, the new type option allows for additional preload targets beyond frame.
// Deprecated
session.setPreloads([path.join(__dirname, 'preload.js')])
// Replace with:
session.registerPreloadScript({
type: 'frame',
id: 'app-preload',
filePath: path.join(__dirname, 'preload.js')
})
Deprecated: level, message, line, and sourceId arguments in console-message event on WebContents
The console-message event on WebContents has been updated to provide details on the Event argument.
// Deprecated
webContents.on('console-message', (event, level, message, line, sourceId) => {})
// Replace with:
webContents.on('console-message', ({ level, message, lineNumber, sourceId, frame }) => {})
Additionally, level is now a string with possible values of info, warning, error, and debug.
Behavior Changed: urls property of WebRequestFilter.
Previously, an empty urls array was interpreted as including all URLs. To explicitly include all URLs, developers should now use the <all_urls> pattern, which is a designated URL pattern that matches every possible URL. This change clarifies the intent and ensures more predictable behavior.
// Deprecated
const deprecatedFilter = {
urls: []
}
// Replace with
const newFilter = {
urls: ['<all_urls>']
}
Устарело: systemPreferences.isAeroGlassEnabled()
The systemPreferences.isAeroGlassEnabled() function has been deprecated without replacement. It has been always returning true since Electron 23, which only supports Windows 10+, where DWM composition can no longer be disabled.
Критические изменения API (34.0)
Behavior Changed: menu bar will be hidden during fullscreen on Windows
This brings the behavior to parity with Linux. Prior behavior: Menu bar is still visible during fullscreen on Windows. New behavior: Menu bar is hidden during fullscreen on Windows.
Correction: This was previously listed as a breaking change in Electron 33, but was first released in Electron 34.
Критические изменения API (33.0)
Устарело: document.execCommand("paste")
The synchronous clipboard read API document.execCommand("paste") has been deprecated in favor of async clipboard API. This is to align with the browser defaults.
The enableDeprecatedPaste option on WebPreferences that triggers the permission checks for this API and the associated permission type deprecated-sync-clipboard-read are also deprecated.
Behavior Changed: frame properties may retrieve detached WebFrameMain instances or none at all
APIs which provide access to a WebFrameMain instance may return an instance with frame.detached set to true, or possibly return null.
When a frame performs a cross-origin navigation, it enters into a detached state in which it's no longer attached to the page. In this state, it may be running unload handlers prior to being deleted. In the event of an IPC sent during this state, frame.detached will be set to true with the frame being destroyed shortly thereafter.
When receiving an event, it's important to access WebFrameMain properties immediately upon being received. Otherwise, it's not guaranteed to point to the same webpage as when received. To avoid misaligned expectations, Electron will return null in the case of late access where the webpage has changed.
ipcMain.on('unload-event', (event) => {
event.senderFrame // ✅ accessed immediately
})
ipcMain.on('unload-event', async (event) => {
await crossOriginNavigationPromise
event.senderFrame // ❌ returns `null` due to late access
})
Behavior Changed: custom protocol URL handling on Windows
Due to changes made in Chromium to support Non-Special Scheme URLs, custom protocol URLs that use Windows file paths will no longer work correctly with the deprecated protocol.registerFileProtocol and the baseURLForDataURL property on BrowserWindow.loadURL, WebContents.loadURL, and <webview>.loadURL. protocol.handle will also not work with these types of URLs but this is not a change since it has always worked that way.
// No longer works
protocol.registerFileProtocol('other', () => {
callback({ filePath: '/path/to/my/file' })
})
const mainWindow = new BrowserWindow()
mainWindow.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', {
baseURLForDataURL: 'other://C:\\myapp'
})
mainWindow.loadURL('other://C:\\myapp\\index.html')
// Replace with
const path = require('node:path')
const nodeUrl = require('node:url')
protocol.handle(other, (req) => {
const srcPath = 'C:\\myapp\\'
const reqURL = new URL(req.url)
return net.fetch(nodeUrl.pathToFileURL(path.join(srcPath, reqURL.pathname)).toString())
})
mainWindow.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: 'other://' })
mainWindow.loadURL('other://index.html')
Behavior Changed: webContents property on login on app
The webContents property in the login event from app will be null when the event is triggered for requests from the utility process created with respondToAuthRequestsFromMainProcess option.
Deprecated: textured option in BrowserWindowConstructorOption.type
The textured option of type in BrowserWindowConstructorOptions has been deprecated with no replacement. This option relied on the NSWindowStyleMaskTexturedBackground style mask on macOS, which has been deprecated with no alternative.
Removed: macOS 10.15 support
macOS 10.15 (Catalina) is no longer supported by Chromium.
Older versions of Electron will continue to run on Catalina, but macOS 11 (Big Sur) or later will be required to run Electron v33.0.0 and higher.
Behavior Changed: Native modules now require C++20
Due to changes made upstream, both V8 and Node.js now require C++20 as a minimum version. Developers using native node modules should build their modules with --std=c++20 rather than --std=c++17. Images using gcc9 or lower may need to update to gcc10 in order to compile. See #43555 for more details.
Deprecated: systemPreferences.accessibilityDisplayShouldReduceTransparency
The systemPreferences.accessibilityDisplayShouldReduceTransparency property is now deprecated in favor of the new nativeTheme.prefersReducedTransparency, which provides identical information and works cross-platform.
// Deprecated
const shouldReduceTransparency = systemPreferences.accessibilityDisplayShouldReduceTransparency
// Replace with:
const prefersReducedTransparency = nativeTheme.prefersReducedTransparency
Критические изменения API (32.0)
Removed: File.path
The nonstandard path property of the Web File object was added in an early version of Electron as a convenience method for working with native files when doing everything in the renderer was more common. However, it represents a deviation from the standard and poses a minor security risk as well, so beginning in Electron 32.0 it has been removed in favor of the webUtils.getPathForFile method.
// Before (renderer)
const file = document.querySelector('input[type=file]').files[0]
alert(`Uploaded file path was: ${file.path}`)
// After (renderer)
const file = document.querySelector('input[type=file]').files[0]
electron.showFilePath(file)
// (preload)
const { contextBridge, webUtils } = require('electron')
contextBridge.exposeInMainWorld('electron', {
showFilePath(file) {
// It's best not to expose the full file path to the web content if
// possible.
const path = webUtils.getPathForFile(file)
alert(`Uploaded file path was: ${path}`)
}
})
Deprecated: clearHistory, canGoBack, goBack, canGoForward, goForward, goToIndex, canGoToOffset, goToOffset on WebContents
The navigation-related APIs are now deprecated.
These APIs have been moved to the navigationHistory property of WebContents to provide a more structured and intuitive interface for managing navigation history.
// Deprecated
win.webContents.clearHistory()
win.webContents.canGoBack()
win.webContents.goBack()
win.webContents.canGoForward()
win.webContents.goForward()
win.webContents.goToIndex(index)
win.webContents.canGoToOffset()
win.webContents.goToOffset(index)
// Replace with
win.webContents.navigationHistory.clear()
win.webContents.navigationHistory.canGoBack()
win.webContents.navigationHistory.goBack()
win.webContents.navigationHistory.canGoForward()
win.webContents.navigationHistory.goForward()
win.webContents.navigationHistory.canGoToOffset()
win.webContents.navigationHistory.goToOffset(index)
Behavior changed: Directory databases in userData will be deleted
If you have a directory called databases in the directory returned by app.getPath('userData'), it will be deleted when Electron 32 is first run. The databases directory was used by WebSQL, which was removed in Electron 31. Chromium now performs a cleanup that deletes this directory. See issue #45396.
Критические изменения API (31.0)
Removed: WebSQL support
Chromium has removed support for WebSQL upstream, transitioning it to Android only. See Chromium's intent to remove discussion for more information.
Behavior Changed: nativeImage.toDataURL will preserve PNG colorspace
PNG decoder implementation has been changed to preserve colorspace data, the encoded data returned from this function now matches it.
See crbug.com/332584706 for more information.
Behavior Changed: window.flashFrame(bool) will flash dock icon continuously on macOS
This brings the behavior to parity with Windows and Linux. Prior behavior: The first flashFrame(true) bounces the dock icon only once (using the NSInformationalRequest level) and flashFrame(false) does nothing. New behavior: Flash continuously until flashFrame(false) is called. This uses the NSCriticalRequest level instead. To explicitly use NSInformationalRequest to cause a single dock icon bounce, it is still possible to use dock.bounce('informational').
Критические изменения API (30.0)
Behavior Changed: cross-origin iframes now use Permission Policy to access features
Cross-origin iframes must now specify features available to a given iframe via the allow attribute in order to access them.
See documentation for more information.
Removed: The --disable-color-correct-rendering switch
This switch was never formally documented but its removal is being noted here regardless. Chromium itself now has better support for color spaces so this flag should not be needed.
Behavior Changed: BrowserView.setAutoResize behavior on macOS
In Electron 30, BrowserView is now a wrapper around the new WebContentsView API.
Previously, the setAutoResize function of the BrowserView API was backed by autoresizing on macOS, and by a custom algorithm on Windows and Linux. For simple use cases such as making a BrowserView fill the entire window, the behavior of these two approaches was identical. However, in more advanced cases, BrowserViews would be autoresized differently on macOS than they would be on other platforms, as the custom resizing algorithm for Windows and Linux did not perfectly match the behavior of macOS's autoresizing API. The autoresizing behavior is now standardized across all platforms.
If your app uses BrowserView.setAutoResize to do anything more complex than making a BrowserView fill the entire window, it's likely you already had custom logic in place to handle this difference in behavior on macOS. If so, that logic will no longer be needed in Electron 30 as autoresizing behavior is consistent.
Deprecated: BrowserView
The BrowserView class has been deprecated and replaced by the new WebContentsView class.
BrowserView related methods in BrowserWindow have also been deprecated:
BrowserWindow.fromBrowserView(browserView)
win.setBrowserView(browserView)
win.getBrowserView()
win.addBrowserView(browserView)
win.removeBrowserView(browserView)
win.setTopBrowserView(browserView)
win.getBrowserViews()
Removed: params.inputFormType property on context-menu on WebContents
The inputFormType property of the params object in the context-menu event from WebContents has been removed. Use the new formControlType property instead.
Удален: process.getIOCounters()
Chromium has removed access to this information.
Критические изменения API (29.0)
Behavior Changed: ipcRenderer can no longer be sent over the contextBridge
Attempting to send the entire ipcRenderer module as an object over the contextBridge will now result in an empty object on the receiving side of the bridge. This change was made to remove / mitigate a security footgun. You should not directly expose ipcRenderer or its methods over the bridge. Instead, provide a safe wrapper like below:
contextBridge.exposeInMainWorld('app', {
onEvent: (cb) => ipcRenderer.on('foo', (e, ...args) => cb(args))
})
Removed: renderer-process-crashed event on app
The renderer-process-crashed event on app has been removed. Use the new render-process-gone event instead.
// Removed
app.on('renderer-process-crashed', (event, webContents, killed) => {
/* ... */
})
// Replace with
app.on('render-process-gone', (event, webContents, details) => {
/* ... */
})
Removed: crashed event on WebContents and <webview>
The crashed events on WebContents and <webview> have been removed. Use the new render-process-gone event instead.
// Removed
win.webContents.on('crashed', (event, killed) => {
/* ... */
})
webview.addEventListener('crashed', (event) => {
/* ... */
})
// Replace with
win.webContents.on('render-process-gone', (event, details) => {
/* ... */
})
webview.addEventListener('render-process-gone', (event) => {
/* ... */
})
Removed: gpu-process-crashed event on app
The gpu-process-crashed event on app has been removed. Use the new child-process-gone event instead.
// Removed
app.on('gpu-process-crashed', (event, killed) => {
/* ... */
})
// Replace with
app.on('child-process-gone', (event, details) => {
/* ... */
})
Критические изменения API (28.0)
Behavior Changed: WebContents.backgroundThrottling set to false affects all WebContents in the host BrowserWindow
WebContents.backgroundThrottling set to false will disable frames throttling in the BrowserWindow for all WebContents displayed by it.
Удален: BrowserWindow.setTrafficLightPosition(position)
BrowserWindow.setTrafficLightPosition(position) has been removed, the BrowserWindow.setWindowButtonPosition(position) API should be used instead which accepts null instead of { x: 0, y: 0 } to reset the position to system default.
// 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() has been removed, the BrowserWindow.getWindowButtonPosition() API should be used instead which returns null instead of { x: 0, y: 0 } when there is no custom position.
// 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()
The ipcRenderer.sendTo() API has been removed. It should be replaced by setting up a MessageChannel between the renderers.
The senderId and senderIsMainFrame properties of IpcRendererEvent have been removed as well.
Удален: app.runningUnderRosettaTranslation
The app.runningUnderRosettaTranslation property has been removed. Вместо него используйте app.runningUnderARM64Translation.
// Removed
console.log(app.runningUnderRosettaTranslation)
// Replace with
console.log(app.runningUnderARM64Translation)
Deprecated: renderer-process-crashed event on app
The renderer-process-crashed event on app has been deprecated. Use the new render-process-gone event instead.
// Deprecated
app.on('renderer-process-crashed', (event, webContents, killed) => {
/* ... */
})
// Replace with
app.on('render-process-gone', (event, webContents, details) => {
/* ... */
})
Deprecated: params.inputFormType property on context-menu on WebContents
The inputFormType property of the params object in the context-menu event from WebContents has been deprecated. Use the new formControlType property instead.
Deprecated: crashed event on WebContents and <webview>
The crashed events on WebContents and <webview> have been deprecated. Use the new render-process-gone event instead.
// Deprecated
win.webContents.on('crashed', (event, killed) => {
/* ... */
})
webview.addEventListener('crashed', (event) => {
/* ... */
})
// Replace with
win.webContents.on('render-process-gone', (event, details) => {
/* ... */
})
webview.addEventListener('render-process-gone', (event) => {
/* ... */
})
Deprecated: gpu-process-crashed event on app
The gpu-process-crashed event on app has been deprecated. Use the new child-process-gone event instead.
// Deprecated
app.on('gpu-process-crashed', (event, killed) => {
/* ... */
})
// Replace with
app.on('child-process-gone', (event, details) => {
/* ... */
})
Критические изменения API (27.0)
Removed: macOS 10.13 / 10.14 support
macOS 10.13 (High Sierra) and macOS 10.14 (Mojave) are no longer supported by Chromium.
Older versions of Electron will continue to run on these operating systems, but macOS 10.15 (Catalina) or later will be required to run Electron v27.0.0 and higher.
Устарело: ipcRenderer.sendTo()
The ipcRenderer.sendTo() API has been deprecated. It should be replaced by setting up a MessageChannel between the renderers.
The senderId and senderIsMainFrame properties of IpcRendererEvent have been deprecated as well.
Removed: color scheme events in systemPreferences
The following systemPreferences events have been removed:
inverted-color-scheme-changedhigh-contrast-color-scheme-changed
Use the new updated event on the nativeTheme module instead.
// Removed
systemPreferences.on('inverted-color-scheme-changed', () => {
/* ... */
})
systemPreferences.on('high-contrast-color-scheme-changed', () => {
/* ... */
})
// Replace with
nativeTheme.on('updated', () => {
/* ... */
})
Removed: Some window.setVibrancy options on macOS
The following vibrancy options have been removed:
- 'light'
- 'medium-light'
- 'dark'
- 'ultra-dark'
- 'appearance-based'
These were previously deprecated and have been removed by Apple in 10.15.
Удален: webContents.getPrinters
The webContents.getPrinters method has been removed. Используйте вместо него webContents.getPrintersAsync.
const w = new BrowserWindow({ show: false })
// Removed
console.log(w.webContents.getPrinters())
// Replace with
w.webContents.getPrintersAsync().then((printers) => {
console.log(printers)
})
Removed: systemPreferences.{get,set}AppLevelAppearance and systemPreferences.appLevelAppearance
The systemPreferences.getAppLevelAppearance and systemPreferences.setAppLevelAppearance methods have been removed, as well as the systemPreferences.appLevelAppearance property. Вместо этого используйте модуль nativeTheme.
// Removed
systemPreferences.getAppLevelAppearance()
// Replace with
nativeTheme.shouldUseDarkColors
// Removed
systemPreferences.appLevelAppearance
// Replace with
nativeTheme.shouldUseDarkColors
// Removed
systemPreferences.setAppLevelAppearance('dark')
// Replace with
nativeTheme.themeSource = 'dark'
Removed: alternate-selected-control-text value for systemPreferences.getColor
The alternate-selected-control-text value for systemPreferences.getColor has been removed. Вместо него используйте 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 })
// Устарело
console.log(w.webContents.getPrinters())
// Заменить на
w.webContents.getPrintersAsync().then((printers) => {
console.log(printers)
})
Устарело: systemPreferences.{get,set}AppLevelAppearance и systemPreferences.appLevelAppearance
Методы systemPreferences.getAppLevelAppearance и systemPreferences.setAppLevelAppearance устарели, так же как и свойство systemPreferences.appLevelAppearance. Вместо этого используйте модуль nativeTheme.
// Устарело
systemPreferences.getAppLevelAppearance()
// Заменить на
nativeTheme.shouldUseDarkColors
// Устарело
systemPreferences.appLevelAppearance
// Заменить на
nativeTheme.shouldUseDarkColors
// Устарело
systemPreferences.setAppLevelAppearance('dark')
// Заменить на
nativeTheme.themeSource = 'dark'
Устарело: значение alternate-selected-control-text для systemPreferences.getColor
Значение alternate-selected-control-text для systemPreferences.getColor устарело. Вместо него используйте selected-content-background.
// Устарело
systemPreferences.getColor('alternate-selected-control-text')
// Заменить на
systemPreferences.getColor('selected-content-background')
Критические изменения API (25.0)
Deprecated: protocol.{un,}{register,intercept}{Buffer,String,Stream,File,Http}Protocol and protocol.isProtocol{Registered,Intercepted}
Методы protocol.register*Protocol и protocol.intercept*Protocol заменены на protocol.handle.
The new method can either register a new protocol or intercept an existing protocol, and responses can be of any type.
// Устарело в Electron 25
protocol.registerBufferProtocol('some-protocol', () => {
callback({ mimeType: 'text/html', data: Buffer.from('<h5>Response</h5>') })
})
// Заменить на
protocol.handle('some-protocol', () => {
return new Response(
Buffer.from('<h5>Response</h5>'), // Could also be a string or ReadableStream.
{ headers: { 'content-type': 'text/html' } }
)
})
// Устарело в Electron 25
protocol.registerHttpProtocol('some-protocol', () => {
callback({ url: 'https://electronjs.org' })
})
// Заменить на
protocol.handle('some-protocol', () => {
return net.fetch('https://electronjs.org')
})
// 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')
})
Obsoleto: BrowserWindow.setTrafficLightPosition(position)
BrowserWindow.setTrafficLightPosition(position) has been deprecated, the BrowserWindow.setWindowButtonPosition(position) API should be used instead which accepts null instead of { x: 0, y: 0 } to reset the position to system default.
// 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)
Obsoleto: BrowserWindow.getTrafficLightPosition()
BrowserWindow.getTrafficLightPosition() has been deprecated, the BrowserWindow.getWindowButtonPosition() API should be used instead which returns null instead of { x: 0, y: 0 } when there is no custom position.
// 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)
The maxSize parameter has been changed to size to reflect that the size passed in will be the size the thumbnail created. Previously, Windows would not scale the image up if it were smaller than maxSize, and macOS would always set the size to maxSize. Behavior is now the same across platforms.
Updated Behavior:
// a 128x128 image.
const imagePath = path.join('path', 'to', 'capybara.png')
// Scaling up a smaller image.
const upSize = { width: 256, height: 256 }
nativeImage.createThumbnailFromPath(imagePath, upSize).then((result) => {
console.log(result.getSize()) // { width: 256, height: 256 }
})
// Scaling down a larger image.
const downSize = { width: 64, height: 64 }
nativeImage.createThumbnailFromPath(imagePath, downSize).then((result) => {
console.log(result.getSize()) // { width: 64, height: 64 }
})
Previous Behavior (on Windows):
// a 128x128 image
const imagePath = path.join('path', 'to', 'capybara.png')
const size = { width: 256, height: 256 }
nativeImage.createThumbnailFromPath(imagePath, size).then((result) => {
console.log(result.getSize()) // { width: 128, height: 128 }
})
Критические изменения API (23.0)
Behavior Changed: Draggable Regions on macOS
The implementation of draggable regions (using the CSS property -webkit-app-region: drag) has changed on macOS to bring it in line with Windows and Linux. Previously, when a region with -webkit-app-region: no-drag overlapped a region with -webkit-app-region: drag, the no-drag region would always take precedence on macOS, regardless of CSS layering. That is, if a drag region was above a no-drag region, it would be ignored. Beginning in Electron 23, a drag region on top of a no-drag region will correctly cause the region to be draggable.
Additionally, the customButtonsOnHover BrowserWindow property previously created a draggable region which ignored the -webkit-app-region CSS property. This has now been fixed (see #37210 for discussion).
As a result, if your app uses a frameless window with draggable regions on macOS, the regions which are draggable in your app may change in Electron 23.
Removed: Windows 7 / 8 / 8.1 support
Windows 7, Windows 8, and Windows 8.1 are no longer supported. Electron follows the planned Chromium deprecation policy, which will deprecate Windows 7 support beginning in Chromium 109.
Older versions of Electron will continue to run on these operating systems, but Windows 10 or later will be required to run Electron v23.0.0 and higher.
Removed: BrowserWindow scroll-touch-* events
The deprecated scroll-touch-begin, scroll-touch-end and scroll-touch-edge events on BrowserWindow have been removed. Instead, use the newly available input-event event on WebContents.
// Removed in Electron 23.0
win.on('scroll-touch-begin', scrollTouchBegin)
win.on('scroll-touch-edge', scrollTouchEdge)
win.on('scroll-touch-end', scrollTouchEnd)
// Replace with
win.webContents.on('input-event', (_, event) => {
if (event.type === 'gestureScrollBegin') {
scrollTouchBegin()
} else if (event.type === 'gestureScrollUpdate') {
scrollTouchEdge()
} else if (event.type === 'gestureScrollEnd') {
scrollTouchEnd()
}
})
Удален: webContents.incrementCapturerCount(stayHidden, stayAwake)
The webContents.incrementCapturerCount(stayHidden, stayAwake) function has been removed. It is now automatically handled by webContents.capturePage when a page capture completes.
const w = new BrowserWindow({ show: false })
// Removed in Electron 23
w.webContents.incrementCapturerCount()
w.capturePage().then((image) => {
console.log(image.toDataURL())
w.webContents.decrementCapturerCount()
})
// Replace with
w.capturePage().then((image) => {
console.log(image.toDataURL())
})
Удален: webContents.decrementCapturerCount(stayHidden, stayAwake)
The webContents.decrementCapturerCount(stayHidden, stayAwake) function has been removed. It is now automatically handled by webContents.capturePage when a page capture completes.
const w = new BrowserWindow({ show: false })
// Removed in Electron 23
w.webContents.incrementCapturerCount()
w.capturePage().then((image) => {
console.log(image.toDataURL())
w.webContents.decrementCapturerCount()
})
// Replace with
w.capturePage().then((image) => {
console.log(image.toDataURL())
})
Критические изменения API (22.0)
Obsoleto: webContents.incrementCapturerCount(stayHidden, stayAwake)
webContents.incrementCapturerCount(stayHidden, stayAwake) has been deprecated. It is now automatically handled by webContents.capturePage when a page capture completes.
const w = new BrowserWindow({ show: false })
// Removed in Electron 23
w.webContents.incrementCapturerCount()
w.capturePage().then((image) => {
console.log(image.toDataURL())
w.webContents.decrementCapturerCount()
})
// Replace with
w.capturePage().then((image) => {
console.log(image.toDataURL())
})
Obsoleto: webContents.decrementCapturerCount(stayHidden, stayAwake)
webContents.decrementCapturerCount(stayHidden, stayAwake) has been deprecated. It is now automatically handled by webContents.capturePage when a page capture completes.
const w = new BrowserWindow({ show: false })
// Removed in Electron 23
w.webContents.incrementCapturerCount()
w.capturePage().then((image) => {
console.log(image.toDataURL())
w.webContents.decrementCapturerCount()
})
// Replace with
w.capturePage().then((image) => {
console.log(image.toDataURL())
})
Removed: WebContents new-window event
The new-window event of WebContents has been removed. It is replaced by webContents.setWindowOpenHandler().
// Removed in Electron 22
webContents.on('new-window', (event) => {
event.preventDefault()
})
// Replace with
webContents.setWindowOpenHandler((details) => {
return { action: 'deny' }
})
Removed: <webview> new-window event
The new-window event of <webview> has been removed. There is no direct replacement.
// Removed in Electron 22
webview.addEventListener('new-window', (event) => {})
// Replace with
// main.js
mainWindow.webContents.on('did-attach-webview', (event, wc) => {
wc.setWindowOpenHandler((details) => {
mainWindow.webContents.send('webview-new-window', wc.id, details)
return { action: 'deny' }
})
})
// preload.js
const { ipcRenderer } = require('electron')
ipcRenderer.on('webview-new-window', (e, webContentsId, details) => {
console.log('webview-new-window', webContentsId, details)
document.getElementById('webview').dispatchEvent(new Event('new-window'))
})
// renderer.js
document.getElementById('webview').addEventListener('new-window', () => {
console.log('got new-window event')
})
Deprecated: BrowserWindow scroll-touch-* events
The scroll-touch-begin, scroll-touch-end and scroll-touch-edge events on BrowserWindow are deprecated. Instead, use the newly available input-event event on WebContents.
// Deprecated
win.on('scroll-touch-begin', scrollTouchBegin)
win.on('scroll-touch-edge', scrollTouchEdge)
win.on('scroll-touch-end', scrollTouchEnd)
// Replace with
win.webContents.on('input-event', (_, event) => {
if (event.type === 'gestureScrollBegin') {
scrollTouchBegin()
} else if (event.type === 'gestureScrollUpdate') {
scrollTouchEdge()
} else if (event.type === 'gestureScrollEnd') {
scrollTouchEnd()
}
})
Критические изменения API (21.0)
Comportement modifié: Cage mémoire V8 activée
The V8 memory cage has been enabled, which has implications for native modules which wrap non-V8 memory with ArrayBuffer or Buffer. See the blog post about the V8 memory cage for more details.
Изменения в API: webContents.printToPDF()
webContents.printToPDF() has been modified to conform to Page.printToPDF in the Chrome DevTools Protocol. This has been changed in order to address changes upstream that made our previous implementation untenable and rife with bugs.
Аргументы изменены
pageRanges
Аргументы удалены
printSelectionOnlymarginsTypeheaderFooterscaleFactor
Arguments Added
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)
Removed: macOS 10.11 / 10.12 support
macOS 10.11 (El Capitan) and macOS 10.12 (Sierra) are no longer supported by Chromium.
Older versions of Electron will continue to run on these operating systems, but macOS 10.13 (High Sierra) or later will be required to run Electron v20.0.0 and higher.
Default Changed: renderers without nodeIntegration: true are sandboxed by default
Previously, renderers that specified a preload script defaulted to being unsandboxed. This meant that by default, preload scripts had access to Node.js. In Electron 20, this default has changed. Beginning in Electron 20, renderers will be sandboxed by default, unless nodeIntegration: true or sandbox: false is specified.
If your preload scripts do not depend on Node, no action is needed. If your preload scripts do depend on Node, either refactor them to remove Node usage from the renderer, or explicitly specify sandbox: false for the relevant renderers.
Removed: skipTaskbar on Linux
On X11, skipTaskbar sends a _NET_WM_STATE_SKIP_TASKBAR message to the X11 window manager. There is not a direct equivalent for Wayland, and the known workarounds have unacceptable tradeoffs (e.g. Window.is_skip_taskbar in GNOME requires unsafe mode), so Electron is unable to support this feature on Linux.
Изменения в API: session.setDevicePermissionHandler(handler)
The handler invoked when session.setDevicePermissionHandler(handler) is used has a change to its arguments. This handler no longer is passed a frame WebFrameMain, but instead is passed the origin, which is the origin that is checking for device permission.
Критические изменения API (19.0)
Removed: IA32 Linux binaries
This is a result of Chromium 102.0.4999.0 dropping support for IA32 Linux. This concludes the removal of support for IA32 Linux.
Критические изменения API (18.0)
Удален: nativeWindowOpen
Prior to Electron 15, window.open was by default shimmed to use BrowserWindowProxy. This meant that window.open('about:blank') did not work to open synchronously scriptable child windows, among other incompatibilities. Начиная с Electron 15, nativeWindowOpen включен по умолчанию.
See the documentation for window.open in Electron for more details.
Критические изменения API (17.0)
Удалено: desktopCapturer.getSources в рендере
API desktopCapturer.getSources теперь доступен только в основном процессе. Это было изменено для того, чтобы улучшить стандартную безопасность приложений 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)
}
Однако следует рассмотреть возможность дальнейшего ограничения информации, возвращаемой в рендереру; например, отображать пользователю селектор источников и только возвращать только выбранный источник.
Deprecated: nativeWindowOpen
Prior to Electron 15, window.open was by default shimmed to use BrowserWindowProxy. This meant that window.open('about:blank') did not work to open synchronously scriptable child windows, among other incompatibilities. Начиная с Electron 15, nativeWindowOpen включен по умолчанию.
See the documentation for window.open in Electron for more details.
Критические изменения API (16.0)
Behavior Changed: crashReporter implementation switched to Crashpad on Linux
The underlying implementation of the crashReporter API on Linux has changed from Breakpad to Crashpad, bringing it in line with Windows and Mac. As a result of this, child processes are now automatically monitored, and calling process.crashReporter.start in Node child processes is no longer needed (and is not advisable, as it will start a second instance of the Crashpad reporter).
There are also some subtle changes to how annotations will be reported on Linux, including that long values will no longer be split between annotations appended with __1, __2 and so on, and instead will be truncated at the (new, longer) annotation value limit.
Deprecated: desktopCapturer.getSources in the renderer
Usage of the desktopCapturer.getSources API in the renderer has been deprecated and will be removed. This change improves the default security of Electron apps.
See here for details on how to replace this API in your app.
Критические изменения API (15.0)
Default Changed: nativeWindowOpen defaults to 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.
Устарело: app.runningUnderRosettaTranslation
The app.runningUnderRosettaTranslation property has been deprecated. Вместо него используйте app.runningUnderARM64Translation.
// Deprecated
console.log(app.runningUnderRosettaTranslation)
// Replace with
console.log(app.runningUnderARM64Translation)
Критические изменения API (14.0)
Removed: remote module
The remote module was deprecated in Electron 12, and will be removed in Electron 14. It is replaced by the @electron/remote module.
// Deprecated in Electron 12:
const { BrowserWindow } = require('electron').remote
// Replace with:
const { BrowserWindow } = require('@electron/remote')
// In the main process:
require('@electron/remote/main').initialize()
Удален: app.allowRendererProcessReuse
The app.allowRendererProcessReuse property will be removed as part of our plan to more closely align with Chromium's process model for security, performance and maintainability.
Для подробностей см. #18397.
Removed: Browser Window Affinity
Параметр affinity при создании нового BrowserWindow будет удален в рамках нашего плана для более тесной связи с моделью процесса Chrome в целях безопасности, производительность и лучшей поддержки.
Для подробностей см. #18397.
Изменения в API: window.open()
Необязательный параметр frameName больше не устанавливает название окна. Теперь это следует спецификации, описанной в документации в соответствии с параметром windowName.
If you were using this parameter to set the title of a window, you can instead use win.setTitle(title).
Удален: worldSafeExecuteJavaScript
В Electron 14 worldSafeExecuteJavaScript будет удален. Альтернатива отсутствует, пожалуйста, убедитесь, что в вашем коде данный параметр включен. Он был включен в Electron по умолчанию
12.
На вас повлияет это изменение, если вы используете либо webFrame.executeJavaScript или webFrame.executeJavaScriptInIsolatedWorld. You will need to ensure that values returned by either of those methods are supported by the Context Bridge API as these methods use the same value passing semantics.
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. Вы должны использовать requestingOrigin, embeddingOrigin и securityOrigin свойства для правильного ответа на проверку. Так как webContents может быть null больше, на него нельзя полагаться.
// Старый код
session.setPermissionCheckHandler((webContents, permission) => {
if (webContents.getURL().startsWith('https://google. om/') && permission === 'notification') {
return true
}
возвращает false
})
// Заменить на
сессию. etPermissionCheckHandler((webContents, permission, requestingOrigin) => {
if (new URL(requestingOrigin). ostname === 'google.com' && permission === 'notification') {
return true
}
возвращает false
})
Удален: shell.moveItemToTrash()
Удален устаревший синхронный shell.moveItemToTrash() API. Вместо этого используйте асинхронный 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()
Использовать 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.addExtension(path)
BrowserWindow.addDevToolsExtension(path)
// Заменить
session.defaultSession.loadExtension(path)
// Удален в Electron 13
BrowserWindow.getExtensions()
BrowserWindow.getDevToolsExtensions()
// Заменить
session.defaultSession.getAllExtensions()
Удалено: методы в systemPreferences
Следующие systemPreferences были устаревшими:
systemPreferences.isDarkMode()systemPreferences.isvertedColorScheme()systemPreferences.isHighContrastColorScheme()
Используйте следующие свойства nativeTheme вместо этого:
nativeTheme.shouldUseDarkColorsnativeTheme.shouldUseInvertedColorSchemenativeTheme.shouldUseHighContrastColors
// Удалён в Electron 13
systemPreferences.isDarkMode()
// Заменить на
nativeTheme.shouldUseDarkColors
// Удалён в Electron 13
systemPreferences. sInvertedColorScheme()
// Заменить на
nativeTheme.shouldUseInvertedColorScheme
// Удалено в Electron 13
systemPreferences.isHighContrastColorScheme()
// Заменить на
nativeTheme.shouldUseHighContrastColors
Устарело: WebContents new-window событие
Событие new-window сетевого контента является устаревшим. It is replaced by webContents.setWindowOpenHandler().
// Устарел в Electron 13
webContents.on('new-window', (event) => {
событие. reventDefault()
})
// Заменить на
webContents.setWindowOpenHandler((details) => {
return { action: 'deny' }
})
Критические изменения API (12.0)
Удалено: Поддержка Pepper Flash
Chromium удалил поддержку Flash, и поэтому мы должны следовать этому примеру. Смотрите Chromium Flash Roadmap для получения более подробной информации.
Default Changed: worldSafeExecuteJavaScript defaults to true
В Electron 12, worldSafeExecuteJavaScript будет включен по умолчанию. Чтобы восстановить предыдущее поведение, в WebPreferences должен быть определен worldSafeExecuteJavaScript: false. Обратите внимание, что установливать этого параметр в false небезопасно.
This option will be removed in Electron 14 so please migrate your code to support the default value.
Default Changed: contextIsolation defaults to true
We recommend having contextIsolation enabled for the security of your application.
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()
The crashReporter.getCrashesDirectory method has been removed. Usage should be replaced by app.getPath('crashDumps').
// Removed in Electron 12
crashReporter.getCrashesDirectory()
// Replace with
app.getPath('crashDumps')
Removed: crashReporter methods in the renderer process
The following crashReporter methods are no longer available in the renderer process:
crashReporter.startcrashReporter.getLastCrashReportcrashReporter.getUploadedReportscrashReporter.getUploadToServerвылетать Reporter.setUploadToServercrashReporter.getCrashesDirectory
They should be called only from the main process.
See #23265 for more details.
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.
Deprecated: remote module
The remote module is deprecated in Electron 12, and will be removed in Electron 14. It is replaced by the @electron/remote module.
// Deprecated in Electron 12:
const { BrowserWindow } = require('electron').remote
// Replace with:
const { BrowserWindow } = require('@electron/remote')
// In the main process:
require('@electron/remote/main').initialize()
Устарело: shell.moveItemToTrash()
The synchronous shell.moveItemToTrash() has been replaced by the new, asynchronous shell.trashItem().
// Deprecated in Electron 12
shell.moveItemToTrash(path)
// Replace with
shell.trashItem(path).then(/* ... */)
Критические изменения API (11.0)
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' } })
Obsoleto: crashReporter.getCrashesDirectory()
Метод crashReporter.getCrashesDirectory устарел. Usage should be replaced by app.getPath('crashDumps').
// Deprecated in Electron 10
crashReporter.getCrashesDirectory()
// Replace with
app.getPath('crashDumps')
Deprecated: crashReporter methods in the renderer process
Calling the following crashReporter methods from the renderer process is deprecated:
crashReporter.startcrashReporter.getLastCrashReportcrashReporter.getUploadedReportscrashReporter.getUploadToServerвылетать Reporter.setUploadToServercrashReporter.getCrashesDirectory
The only non-deprecated methods remaining in the crashReporter module in the renderer are addExtraParameter, removeExtraParameter and getParameters.
All above methods remain non-deprecated when called from the main process.
See #23265 for more details.
Устарело: crashReporter.start({ compress: false })
Setting { compress: false } in crashReporter.start is deprecated. Nearly all crash ingestion servers support gzip compression. This option will be removed in a future version of Electron.
Изменение значения по-умолчанию: enableRemoteModule изменено на false
In Electron 9, using the remote module without explicitly enabling it via the enableRemoteModule WebPreferences option began emitting a warning. In Electron 10, the remote module is now disabled by default. To use the remote module, enableRemoteModule: true must be specified in WebPreferences:
const w = new BrowserWindow({
webPreferences: {
enableRemoteModule: true
}
})
We recommend moving away from the remote module.
protocol.unregisterProtocol
protocol.uninterceptProtocol
API теперь синхронизируются, и необязательный обратный вызов больше не требуется.
// 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)
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.
Для подробностей см. #18397.
Deprecated: BrowserWindow extension APIs
The following extension APIs have been deprecated:
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()
Removed: <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. The function was deprecated in Electron 8.x, and has been removed in Electron 9.x. The layout zoom level limits are now fixed at a minimum of 0.25 and a maximum of 5.0, as defined here.
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,Infinityand-Infinitywill now be correctly serialized, instead of being converted tonull.- Objects containing cyclic references will now be correctly serialized, instead of being converted to
null. Set,Map,ErrorandRegExpvalues will be correctly serialized, instead of being converted to{}.BigIntvalues will be correctly serialized, instead of being converted tonull.- Sparse arrays will be serialized as such, instead of being converted to dense arrays with
nulls. Dateobjects will be transferred asDateobjects, instead of being converted to their ISO string representation.- Typed Arrays (such as
Uint8Array,Uint16Array,Uint32Arrayand so on) will be transferred as such, instead of being converted to Node.jsBuffer. - Node.js
Bufferobjects will be transferred asUint8Arrays. You can convert aUint8Arrayback to a Node.jsBufferby wrapping the underlyingArrayBuffer:
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())
Устарело: 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-changedhigh-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', () => {
/* ... */
})
Deprecated: methods in systemPreferences
Следующие systemPreferences были устаревшими:
systemPreferences.isDarkMode()systemPreferences.isvertedColorScheme()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)
Deprecated: Atom.io Node Headers URL
Это URL, указанный как disturl в файле .npmrc или как --dist-url флаг командной строки, при сборке нативных модулей Node. Оба будут поддерживаться в обозримом будущем, но рекомендуется переключиться.
Устарело: https://atom.io/download/electron
Заменено на: https://electronjs.org/headers
API Changed: session.clearAuthCache() no longer accepts options
session.clearAuthCache API больше не принимает параметры для очистки, а вместо этого безоговорочно очищает весь кэш.
// Устарело
session.clearAuthCache({ type: 'password' })
// Заменить на
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
Это свойство было удалено в Chromium 77, и как таковое больше не доступно.
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).
В качестве иллюстрации возьмем папку с такой структурой:
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 больше не возвращает путь к выбранной папке. 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()#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
These functions now have two forms, synchronous and Promise-based asynchronous:
dialog.showMessageBox()/dialog.showMessageBoxSync()#17298dialog.showOpenDialog()/dialog.showOpenDialogSync()#16973dialog.showSaveDialog()/dialog.showSaveDialogSync()#17054
Критические изменения API (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
// Устарело
app.enableMixedSandbox()
Режим смешанной песочницы теперь включен по умолчанию.
Устарело: Tray.setHighlightMode
Под macOS Catalina наша прежняя реализация Tray нарушена. Нативная замена Apple не поддерживает изменение поведения подсветки.
// Устарело
tray.setHighlightMode(mode)
// Метод будет удален в v7.0 без альтернатив.
Критические изменения API (5.0)
Default Changed: nodeIntegration and webviewTag default to false, contextIsolation defaults to true
Следующие значения по умолчанию для параметра webPreferences устарели в пользу новых значений по умолчанию, перечисленных ниже.
| Свойство | Устаревшее | Новое |
|---|---|---|
contextIsolation | false | true |
nodeIntegration | true | false |
webviewTag | nodeIntegration, если установлено, иначе true | false |
Например, 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
API графического процесса webFrame.registerURLSchemeAsPrivileged и webFrame.registerURLSchemeAsBypassingCSP, а также API процесса браузера protocol.registerStandardSchemes были удалены. Новый API protocol.registerSchemesAsPrivileged был добавлен и должен использоваться для регистрации пользовательских схем с необходимыми привилегиями. Пользовательские схемы должны быть зарегистрированы до готовности приложения.
Deprecated: webFrame.setIsolatedWorld* replaced with webFrame.setIsolatedWorldInfo
// Deprecated
webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp)
webFrame.setIsolatedWorldHumanReadableName(worldId, name)
webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin)
// Replace with
webFrame.setIsolatedWorldInfo(worldId, {
securityOrigin: 'some_origin',
name: 'human_readable_name',
csp: 'content_security_policy'
})
API Changed: webFrame.setSpellCheckProvider now takes an asynchronous callback
Параметр 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 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)
Следующий список включает в себя критические изменения API, сделанные в Electron 4.0.
app.makeSingleInstance
// Deprecated
app.makeSingleInstance((argv, cwd) => {
/* ... */
})
// Replace with
app.requestSingleInstanceLock()
app.on('second-instance', (event, argv, cwd) => {
/* ... */
})
app.releaseSingleInstance
// Устарело
app.releaseSingleInstance()
// Заменят на
app.releaseSingleInstanceLock()
app.getGPUInfo
app.getGPUInfo('complete')
// Теперь ведет себя так же, как `basic` на macOS
app.getGPUInfo('basic')
win_delay_load_hook
При создании нативных модулей для Windows, переменная win_delay_load_hook в binding.gyp модуля должна быть true (это значение по умолчанию). Если этот хук отсутствует, тогда нативный модуль на Windows неудачно загрузится, с сообщением об ошибке, например Cannot find module. See the native module guide for more.
Removed: IA32 Linux support
Electron 18 will no longer run on 32-bit Linux systems. See discontinuing support for 32-bit Linux for more information.
Критические изменения API (3.0)
Данный список включает в себя критические изменения в API для Electron 3.0.
app
// Устарело
app.getAppMemoryInfo()
// Заменено на
app.getAppMetrics()
// Устарело
const metrics = app.getAppMetrics()
const { memory } = metrics[0] // свойство устарело
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
// Устарело
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)
// Нет замены для этого метода
webFrame
// Устарело
webFrame.registerURLSchemeAsSecure('app')
// Заменено на
protocol.registerStandardSchemes(['app'], { secure: true })
// Устарело
webFrame.registerURLSchemeAsPrivileged('app', { secure: true })
// Заменено на
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 */
}
URL заголовков Node
Это URL, указанный как disturl в файле .npmrc или как --dist-url флаг командной строки, при сборке нативных модулей Node.
Устарело: https://atom.io/download/atom-shell
Заменено на: https://atom.io/download/electron
Критические изменения API (2.0)
Следующий список включает в себя критические изменения API, сделанные в Electron 2.0.
autoUpdater
// Deprecated
autoUpdater.setFeedURL(url, headers)
// Replace with
autoUpdater.setFeedURL({
url,
headers
})
BrowserWindow
// Deprecated
const optionsA = { titleBarStyle: 'hidden-inset' }
const windowA = new BrowserWindow(optionsA)
// Replace with
const optionsB = { titleBarStyle: 'hiddenInset' }
const windowB = new BrowserWindow(optionsB)
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.electronиprocess.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.zip и electron-v1.7.3-linux-armv7l.zip. Ресурс с префиксом v7l был добавлен, чтобы уточнить для пользователей, какую версию ARM он поддерживает, и чтобы исключить их в будущих ресурсах armv6l и arm64, которые могут быть произведены.
Файл без префикса по-прежнему публикуется, чтобы избежать нарушения любых настроек, которые могут его использовать. Начиная с версии 2.0, файл без префикса более не будет публиковаться.