Saltar al contenido principal

Actualización de aplicaciones

There are several ways to provide automatic updates to your Electron application. The easiest and officially supported one is taking advantage of the built-in Squirrel framework and Electron's autoUpdater module.

Usando update.electronjs.org

El equipo de Electron mantiene update.electronjs.org, un webservice gratis y open-source que las aplicaciones Electron puede usar para auto-actualizarse. El servicio está diseñado para aplicaciones de Electron que cumplen con los siguientes criterios:

  • Aplicaciones que se ejecuten en macOS o Windows
  • La Aplicación tiene un repositorio público en GitHub
  • Builds are published to GitHub Releases
  • Builds are code-signed

La forma más fácil de usar este servicio es instalando update-electron-app, un módulo de Node.js preconfigurado para usarse con update.electronjs.org.

Install the module using your Node.js package manager of choice:

npm install update-electron-app

Then, invoke the updater from your app's main process file:

main.js
require('update-electron-app')()

De manera predeterminada, este módulo verificará si existen actualizaciones en el inicio de la aplicación y luego cada diez minutos. Cuando se encuentra una actualización, esta se descargará automáticamente en segundo plano. When the download completes, a dialog is displayed allowing the user to restart the app.

If you need to customize your configuration, you can pass options to update-electron-app or use the update service directly.

Using other update services

Si está desarrollando una aplicación privada de Electrón, o si no está publicando lanzamientos en GitHub, tal vez pueda considerar poseer su propio servidor de actualizaciones.

Step 1: Deploying an update server

Dependiendo de sus necesidades, puede escoger una de esta:

  • Hazel – Update server for private or open-source apps which can be deployed for free on Vercel. Es tomado de los Lanzamientos de GitHub y aprovecha al maximo el poder de las CDN's de GitHub.
  • Nuts – También usa los Lanzamientos de GitHub, pero almacena la aplicación, actualiza en el Disco Duro y también soporta repositorios privados.
  • electron-release-server – proporciona un panel para administrar los lanzamientos y no es necesarios que los lanzamientos se originen desde GitHub.
  • Nucleus – Un servidor de actualizaciones completo para aplicaciones de Electrón y es mantenido gracias a Atlassian. Soporta múltiples aplicaciones y canales, y utiliza un almacén de archivos estáticos para minimizar el coste del servidor.

Once you've deployed your update server, you can instrument your app code to receive and apply the updates with Electron's autoUpdater module.

Step 2: Receiving updates in your app

First, import the required modules in your main process code. The following code might vary for different server software, but it works like described when using Hazel.

Check your execution environment!

Please ensure that the code below will only be executed in your packaged app, and not in development. You can use the app.isPackaged API to check the environment.

main.js
const { app, autoUpdater, dialog } = require('electron')

Next, construct the URL of the update server feed and tell autoUpdater about it:

main.js
const server = 'https://your-deployment-url.com'
const url = `${server}/update/${process.platform}/${app.getVersion()}`

autoUpdater.setFeedURL({ url })

As the final step, check for updates. The example below will check every minute:

main.js
setInterval(() => {
autoUpdater.checkForUpdates()
}, 60000)

Once your application is packaged, it will receive an update for each new GitHub Release that you publish.

Step 3: Notifying users when updates are available

Ahora que ha configurado el mecanismo de actualización básico para su aplicación, debe asegurarse de que el usuario reciba una notificación cuando haya una actualización. This can be achieved using the autoUpdater API events:

main.js
autoUpdater.on('update-downloaded', (event, releaseNotes, releaseName) => {
const dialogOpts = {
type: 'info',
buttons: ['Restart', 'Later'],
title: 'Application Update',
message: process.platform === 'win32' ? releaseNotes : releaseName,
detail:
'A new version has been downloaded. Restart the application to apply the updates.'
}

dialog.showMessageBox(dialogOpts).then((returnValue) => {
if (returnValue.response === 0) autoUpdater.quitAndInstall()
})
})

Also make sure that errors are being handled. Here's an example for logging them to stderr:

main.js
autoUpdater.on('error', (message) => {
console.error('There was a problem updating the application')
console.error(message)
})
Handling updates manually

Because the requests made by autoUpdate aren't under your direct control, you may find situations that are difficult to handle (such as if the update server is behind authentication). The url field supports the file:// protocol, which means that with some effort, you can sidestep the server-communication aspect of the process by loading your update from a local directory. Here's an example of how this could work.