autoUpdater
Позвольте приложениям автоматически обновляться.
Process: Main
See also: A detailed guide about how to implement updates in your application.
autoUpdater is an EventEmitter.
Платформа заметок
В настоящее время поддерживаются только macOS и Windows. На Linux нет встроенной поддержи автоматического обновление, поэтому рекомендуется использовать менеджер пакетов для обновления вашего приложения.
Кроме того есть некоторые тонкие различия на каждой платформе:
macOS
На macOS модуль autoUpdater построен на Squirrel.Mac, что означает, что Вам не нужно делать каких-либо специальных настроек, чтобы заставить его работать. Для серверных условий, Вы можете прочитать Поддержку сервера. Note that App Transport Security (ATS) applies to all requests made as part of the update process. Приложению, у которого требуется отключить ATS, можно добавить ключ NSAllowsArbitraryLoads в список свойств приложения (plist).
[!IMPORTANT] Your application must be signed for automatic updates on macOS. Это требование
Squirrel.Mac.
Windows
On Windows, the autoUpdater module automatically selects the appropriate update mechanism based on how your app is packaged:
- MSIX packages: If your app is running as an MSIX package (created with electron-windows-msix and detected via
process.windowsStore), the module uses the MSIX updater, which supports direct MSIX file links and JSON update feeds. - Squirrel.Windows: For apps installed via traditional installers (created with electron-winstaller or Electron Forge's Squirrel.Windows maker), the module uses Squirrel.Windows for updates.
You don't need to configure which updater to use; Electron automatically detects the packaging format and uses the appropriate one.
Squirrel.Windows
Apps built with Squirrel.Windows will trigger custom launch events that must be handled by your Electron application to ensure proper setup and teardown.
Squirrel.Windows apps will launch with the --squirrel-firstrun argument immediately after installation. During this time, Squirrel.Windows will obtain a file lock on your app, and autoUpdater requests will fail until the lock is released. In practice, this means that you won't be able to check for updates on first launch for the first few seconds. You can work around this by not checking for updates when process.argv contains the --squirrel-firstrun flag or by setting a 10-second timeout on your update checks (see electron/electron#7155 for more information).
The installer generated with Squirrel.Windows will create a shortcut icon with an Application User Model ID in the format of com.squirrel.PACKAGE_ID.YOUR_EXE_WITHOUT_DOT_EXE, examples are com.squirrel.slack.Slack and com.squirrel.code.Code. Вы должны использовать тот же ID для Вашего приложения в app.setAppUserModelId API, иначе Windows не сможет должным образом закрепить приложение в панели задач.
MSIX Packages
When your app is packaged as an MSIX, the autoUpdater module provides additional functionality:
- Use the
allowAnyVersionoption insetFeedURL()to allow updates to older versions (downgrades) - Support for direct MSIX file links or JSON update feeds (similar to Squirrel.Mac format)
События
Объект autoUpdater имеет следующие события:
Событие: 'error'
Возвращает:
errorError
Происходит, когда возникает ошибка во время обновления.
Событие: 'checking-for-update'
Emitted when checking for an available update has started.
Событие: 'update-available'
Происходит при наличии доступного обновления. Обновление загружается автоматически.
Событие: 'update-not-available'
Происходит, когда нет доступных обновлений.
Событие: 'update-downloaded'
Возвращает:
eventEventreleaseNotesstringreleaseNamestringreleaseDateDateupdateURLstring
Происходит, когда обновление было загружено.
With Squirrel.Windows only releaseName is available.
[!NOTE] It is not strictly necessary to handle this event. A successfully downloaded update will still be applied the next time the application starts.
Событие: 'before-quit-for-update'
added:
- pr-url: https://github.com/electron/electron/pull/12619
Это событие происходит после вызова quitAndInstall().
Когда это API вызывается, событие before-quit не будет происходить, до тех пор, пока все окна не будут закрыты. В результате Вы должны прослушивать это событие, если хотите выполнить действия до закрытия окон, во время завершения процесса, а также прослушивать before-quit.
Методы
Объект autoUpdater имеет следующие методы:
autoUpdater.setFeedURL(options)
changes:
- pr-url: https://github.com/electron/electron/pull/5879
description: "Added `headers` as a second parameter."
- pr-url: https://github.com/electron/electron/pull/11925
description: "Changed API to accept a single `options` argument (contains `url`, `headers`, and `serverType` properties)."
Задает url и инициализирует автоматическое обновление.
autoUpdater.getFeedURL()
string - возвращает URL текущей подписки обновления.
autoUpdater.checkForUpdates()
Спрашивает сервер, есть ли обновление. Вы должны вызвать setFeedURL перед использованием API.
[!NOTE] If an update is available it will be downloaded automatically. Calling
autoUpdater.checkForUpdates()twice will download the update two times.
autoUpdater.quitAndInstall()
Перезапускает приложение и устанавливает обновление после его загрузки. Следует вызывать только после произошедшего update-downloaded.
Внутри, вызов autoUpdater.quitAndInstall() сначала закроет все окна приложения, и автоматически вызовет app.quit(), после того, как все окна будут закрыты.
[!NOTE] It is not strictly necessary to call this function to apply an update, as a successfully downloaded update will always be applied the next time the application starts.