Критические изменения
Здесь будут описаны критические изменения, а также будут добавлены предупреждения об устаревших функциях в JS коде, где это возможно, по крайней мере перед тем, как изменения будут сделаны в одной мажорной версии.
Типы критических изменений
В этом документе используется следующее соглашение для классификации критических изменений:
- Изменение API: API был изменен таким образом, что код, который не был обновлен, гарантировано бросит исключение.
- Изменение поведения: Поведение Electron было изменено, но не обязательно появление исключений.
- Изменено значение по-умолчанию: Код, работа которого зависит от старого значения по-умолчанию, может сломаться, не обязательно кидая исключение. Старое поведение можно восстановить, если явно указать значение.
- Устарело: API был помечен как устаревший. API продолжит функционировать, но будет появляться предупреждающее сообщение о том, что API будет удален в будущем релизе.
- Удалено: API или функция была удалена и больше не поддерживается Electron.
Запланированные критические изменения 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. Заменяется на webContents.setWindowOpenHandler()
.
// Removed in Electron 22
webContents.on('new-window', (event) => {
event.preventDefault()
})
// Replace with
webContents.setWindowOpenHandler((details) => {
return { action: 'deny' }
})
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 changes in order to address changes upstream that made our previous implementation untenable and rife with bugs.
Аргументы изменены
pageRanges
Аргументы удалены
printSelectionOnly
marginsType
headerFooter
scaleFactor
Arguments Added
headerTemplate
footerTemplate
displayHeaderFooter
margins
scale
preferCSSPageSize
// Main process
const { webContents } = require('electron')
webContents.printToPDF({
landscape: true,
displayHeaderFooter: true,
printBackground: true,
scale: 2,
pageSize: 'Ledger',
margins: {
top: 2,
bottom: 2,
left: 2,
right: 2
},
pageRanges: '1-5, 8, 11-13',
headerTemplate: '<h1>Title</h1>',
footerTemplate: '<div><span class="pageNumber"></span></div>',
preferCSSPageSize: true
}).then(data => {
fs.writeFile(pdfPath, data, (error) => {
if (error) throw error
console.log(`Wrote PDF successfully to ${pdfPath}`)
})
}).catch(error => {
console.log(`Failed to write PDF to ${pdfPath}: `, error)
})
Запланированные критические изменения API (20.0)
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 Changed: 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
включен по умолчанию.
См. документацию по window.open в Electron для более подробной информации.
Запланированные критические изменения 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
включен по умолчанию.
См. документацию по window.open в Electron для более подробной информации.
Запланированные критические изменения 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.
См. документацию по window.open в Electron для более подробной информации.
Запланированные критические изменения 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 Changed: 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
})
Removed: 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.shouldUseDarkColors
nativeTheme.shouldUseInvertedColorScheme
nativeTheme.shouldUseHighContrastColors
// Удалён в Electron 13
systemPreferences.isDarkMode()
// Заменить на
nativeTheme.shouldUseDarkColors
// Удалён в Electron 13
systemPreferences. sInvertedColorScheme()
// Заменить на
nativeTheme.shouldUseInvertedColorScheme
// Удалено в Electron 13
systemPreferences.isHighContrastColorScheme()
// Заменить на
nativeTheme.shouldUseHighContrastColors
Устарело: WebContents new-window
событие
Событие new-window
сетевого контента является устаревшим. Заменяется на 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.start
crashReporter.getLastCrashReport
crashReporter.getUploadedReports
crashReporter.getUploadToServer
вылетать Reporter.setUploadToServer
crashReporter.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()
Obsoleto: 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()
The crashReporter.getCrashesDirectory
method has been deprecated. 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.start
crashReporter.getLastCrashReport
crashReporter.getUploadedReports
crashReporter.getUploadToServer
вылетать Reporter.setUploadToServer
crashReporter.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.
Obsoleto: 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
,Infinity
and-Infinity
will 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
,Error
andRegExp
values will be correctly serialized, instead of being converted to{}
.BigInt
values will be correctly serialized, instead of being converted tonull
.- Sparse arrays will be serialized as such, instead of being converted to dense arrays with
null
s. Date
objects will be transferred asDate
objects, instead of being converted to their ISO string representation.- Typed Arrays (such as
Uint8Array
,Uint16Array
,Uint32Array
and so on) will be transferred as such, instead of being converted to Node.jsBuffer
. - Node.js
Buffer
objects will be transferred asUint8Array
s. You can convert aUint8Array
back to a Node.jsBuffer
by 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.
Obsoleto: <webview>.getWebContents()
This API is implemented using the remote
module, which has both performance and security implications. Therefore its usage should be explicit.
// Deprecated
webview.getWebContents()
// Replace with
const { remote } = require('electron')
remote.webContents.fromId(webview.getWebContentsId())
However, it is recommended to avoid using the remote
module altogether.
// main
const { ipcMain, webContents } = require('electron')
const getGuestForWebContents = (webContentsId, contents) => {
const guest = webContents.fromId(webContentsId)
if (!guest) {
throw new Error(`Invalid webContentsId: ${webContentsId}`)
}
if (guest.hostWebContents !== contents) {
throw new Error('Access denied to webContents')
}
return guest
}
ipcMain.handle('openDevTools', (event, webContentsId) => {
const guest = getGuestForWebContents(webContentsId, event.sender)
guest.openDevTools()
})
// renderer
const { ipcRenderer } = require('electron')
ipcRenderer.invoke('openDevTools', webview.getWebContentsId())
Deprecated: webFrame.setLayoutZoomLevelLimits()
Chromium has removed support for changing the layout zoom level limits, and it is beyond Electron's capacity to maintain it. The function will emit a warning in Electron 8.x, and cease to exist in Electron 9.x. The layout zoom level limits are now fixed at a minimum of 0.25 and a maximum of 5.0, as defined here.
Deprecated events in systemPreferences
The following systemPreferences
events have been deprecated:
inverted-color-scheme-changed
high-contrast-color-scheme-changed
Use the new updated
event on the nativeTheme
module instead.
// Deprecated
systemPreferences.on('inverted-color-scheme-changed', () => { /* ... */ })
systemPreferences.on('high-contrast-color-scheme-changed', () => { /* ... */ })
// Replace with
nativeTheme.on('updated', () => { /* ... */ })
Deprecated: methods in systemPreferences
Следующие systemPreferences
были устаревшими:
systemPreferences.isDarkMode()
systemPreferences.isvertedColorScheme()
systemPreferences.isHighContrastColorScheme()
Используйте следующие свойства nativeTheme
вместо этого:
nativeTheme.shouldUseDarkColors
nativeTheme.shouldUseInvertedColorScheme
nativeTheme.shouldUseHighContrastColors
// Deprecated
systemPreferences.isDarkMode()
// Replace with
nativeTheme.shouldUseDarkColors
// Deprecated
systemPreferences.isInvertedColorScheme()
// Replace with
nativeTheme.shouldUseInvertedColorScheme
// Deprecated
systemPreferences.isHighContrastColorScheme()
// Replace with
nativeTheme.shouldUseHighContrastColors
Запланированные критические изменения API (7.0)
Deprecated: Atom.io Node Headers URL
Это URL, указанный как disturl
в файле .npmrc
или как --dist-url
флаг командной строки, при сборке нативных модулей Node. Оба будут поддерживаться в обозримом будущем, но рекомендуется переключиться.
Deprecated: https://atom.io/download/electron
Replace with: 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
// Удалено в Electron 7.0
webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp)
webFrame.setIsolatedWorldHumanReadableName(worldId, name)
webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin)
// Заменить на
webFrame.setIsolatedWorldInfo(
worldId,
{
securityOrigin: 'some_origin',
name: 'human_readable_name',
csp: 'content_security_policy'
})
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).
As an illustration, take a folder with this structure:
folder
├── file1
├── file2
└── file3
In Electron <=6, this would return a FileList
with a File
object for:
path/to/folder
In Electron 7, this now returns a FileList
with a File
object for:
/path/to/folder/file3
/path/to/folder/file2
/path/to/folder/file1
Note that webkitdirectory
no longer exposes the path to the selected folder. If you require the path to the selected folder rather than the folder contents, see the dialog.showOpenDialog
API (link).
API Changed: Callback-based versions of promisified APIs
Electron 5 and Electron 6 introduced Promise-based versions of existing asynchronous APIs and deprecated their older, callback-based counterparts. In Electron 7, all deprecated callback-based APIs are now removed.
These functions now only return Promises:
app.getFileIcon()
#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()
Режим смешанной песочницы теперь включен по умолчанию.
Deprecated: 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
Renderer process APIs webFrame.registerURLSchemeAsPrivileged
and webFrame.registerURLSchemeAsBypassingCSP
as well as browser process API protocol.registerStandardSchemes
have been removed. Новый API protocol.registerSchemesAsPrivileged
был добавлен и должен использоваться для регистрации пользовательских схем с необходимыми привилегиями. Пользовательские схемы должны быть зарегистрированы до готовности приложения.
Deprecated: webFrame.setIsolatedWorld*
replaced with webFrame.setIsolatedWorldInfo
// Устарело
webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp)
webFrame.setIsolatedWorldHumanReadableName(worldId, name)
webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin)
// Заменено на
webFrame.setIsolatedWorldInfo(
worldId,
{
securityOrigin: 'some_origin',
name: 'human_readable_name',
csp: 'content_security_policy'
})
API Changed: webFrame.setSpellCheckProvider
now takes an asynchronous callback
Параметр spellCheck
теперь асинхронный, а параметр autoCorrectWord
был удален.
// Устаревшее
webFrame.setSpellCheckProvider('en-US', true, {
spellCheck: (text) => {
return !spellchecker. sMisspelled(text)
}
})
// Заменить на
webFrame. etSpellCheckProvider('en-US', {
spellCheck: (words, callback) => {
callback(слова. ilter(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>
// Удалено
webview.setAttribute('disableguestresize', '')
// Нет замены для этого метода
// Удалено
webview.setAttribute('guestinstance', instanceId)
// Нет замены для этого метода
// Слушатели клавиатуры больше не работают в webview теге
webview.onkeydown = () => { /* обработчик */ }
webview.onkeyup = () => { /* обработчик */ }
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.
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, файл без префикса более не будет публиковаться.