Saltar al contenido principal

autoUpdater

Enable apps to automatically update themselves.

Proceso: principal

See also: A detailed guide about how to implement updates in your application.

autoUpdater is an EventEmitter.

Noticias de la plataforma

Actualmente, sólo macOS y Windows son soportados. No hay soporte para auto actualizaciones en Linux, por lo que es recomendable que use el gestor de paquetes de la distribución para actualizar su aplicación.

Adicionalmente, hay algunas diferencias sutiles en cada plataforma:

macOS

En macOS, el módulo autoUpdater está construido sobre Squirrel.Mac, lo que significa que no necesita ninguna configuración especial para que funcione. Para los requisitos de servidor, puede leer Soporte de servidor. Note that App Transport Security (ATS) applies to all requests made as part of the update process. Aplicaciones que necesitan para desactivar ATS pueden agregar la clave de NSAllowsArbitraryLoads a su .plist de su aplicación.

[!IMPORTANT] Your application must be signed for automatic updates on macOS. Este es un requerimiento de Squirrel.Mac.

Windows

On Windows, the autoUpdater module automatically selects the appropriate update mechanism based on how your app is packaged:

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. Tu debes usar el mismo ID de tu aplicación con app.setAppUserModelId API, de lo contrario Windows no podría ejecutarlo correctamente en la barra de tareas.

MSIX Packages

When your app is packaged as an MSIX, the autoUpdater module provides additional functionality:

  • Use the allowAnyVersion option in setFeedURL() to allow updates to older versions (downgrades)
  • Support for direct MSIX file links or JSON update feeds (similar to Squirrel.Mac format)

Eventos

El objeto app emite los siguientes eventos:

Evento: "error"

Devuelve:

  • error Error

Aparece cuando hay un error al actualizar.

Evento: "comprobar si hay actualizaciones"

Emitted when checking for an available update has started.

Evento: "actualización disponible"

Emitido cuando hay una actualización disponible. La actualización es descargada automáticamente.

Evento: 'update-not-available'

Aparece cuando no hay una actualización disponible.

Evento: "actualización descargada"

Devuelve:

  • event Event
  • releaseNotes string
  • releaseName string
  • releaseDate Date
  • updateURL string

Aparece cuando se ha descargado una actualización.

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.

Evento: 'before-quit-for-update'

added:
- pr-url: https://github.com/electron/electron/pull/12619

Este evento se ejecuta luego que un usuario llama al método: quitAndInstall().

Cuando se hace el llamado a la API, el evento before-quit no se ejecuta hasta que todas las ventanas estén cerradas. Como resultado usted debe escuchar a este evento si desea realizar acciones antes de que las ventanas sean cerradas, mientras el proceso está finalizando, así como también escuchar al proceso: before-quit.

Métodos

El objeto autoUpdater tiene los siguientes métodos:

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)."
  • options Object
    • url string - The update server URL. For Windows MSIX, this can be either a direct link to an MSIX file (e.g., https://example.com/update.msix) or a JSON endpoint that returns update information (see the Squirrel.Mac README for more information).
    • headers Record<string, string> (optional) macOS - HTTP request headers.
    • serverType string (opcional) macOS - Puede ser json o default, vea el README de Squirrel.Mac para más información.
    • allowAnyVersion boolean (optional) Windows - If true, allows downgrades to older versions for MSIX packages. Por defecto es false.

Configura el url e inicializa la actualización automática.

autoUpdater.getFeedURL()

Devuelve string - La actualización actual provee el URL.

autoUpdater.checkForUpdates()

Pregunta al servidor si hay una actualización. Debes llamar a setFeedURL antes de usar esta API.

[!NOTE] If an update is available it will be downloaded automatically. Calling autoUpdater.checkForUpdates() twice will download the update two times.

autoUpdater.quitAndInstall()

Reinicia la aplicación e instala la actualización después que esta ha sido descargada. Sólo debería llamarse después de que update-downloaded ha sido emitido.

Llamar a autoUpdater.quitAndInstall() bajo la capucha cerrará todas las ventanas de la aplicación, y llamará automáticamente a app.quit() después de que se hayan cerrado todas las ventanas.

[!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.