Skip to main content




Sincronice los datos de su aplicación Web en segundo plano para una experiencia más nativa


Updated

Have you ever been in any of the following situations?

  • Traveling by train or metro with unstable or no connectivity
  • Your operator sped it up after watching too many videos
  • Living in a country where bandwidth struggles to keep up with demand

Si es así, seguramente ha sentido la frustración de hacer ciertas cosas en la web y se preguntó por qué las aplicaciones nativas a menudo funcionan mejor en estos escenarios. Las aplicaciones nativas pueden obtener contents nuevo, como artículos de noticias o información meteorológica, antes de tiempo. Incluso si no hay red en el metro, aún puede leer las noticias.

Background periodic synchronization allows web applications to periodically synchronize data in the background, bringing web applications closer to the behavior of a native application.

Actual state

La siguiente tabla explica el estado actual de la API de sincronización periódica en segundo plano.

He passed

Condition

1. Create an explainer

To complete

2. Create initial draft specification

To complete

3. Collect feedback and repeat the design

In progress

4. Proof of origin

To complete

5. Launch Chromium 80

Try it

You can test periodic synchronization in the background with the live demo app. Before use, make sure that:

  • You are using Chrome 80 or later.
  • Your
    Install on pc
    the web app before enabling background periodic syncing.

Concepts and usage

Periodic background syncing allows you to display new content when launching a progressive web application or a page supported by a service worker. It does this by downloading data in the background when the app or page is not being used. This prevents the content of the application from updating after launch while it is being viewed. Better yet, prevent the app from displaying a content spinner before updating.

Sin una sincronización periódica en segundo plano, las aplicaciones web deben utilizar métodos alternativos para descargar datos. Un ejemplo común es el uso de una notificación de inserción para despertar a un trabajador del servicio. El Username es interrumpido por un mensaje como «nuevos datos disponibles». Actualizar los datos es esencialmente un efecto secundario. Todavía tiene la opción de usar notificaciones automáticas para actualizaciones realmente importantes, como noticias de última hora importantes.

La sincronización periódica en segundo plano se confunde fácilmente con la sincronización en segundo plano. Aunque tienen nombres similares, sus casos de uso son diferentes. Entre otras cosas, la sincronización en segundo plano se usa más comúnmente para reenviar datos a un server cuando una solicitud anterior ha fallado.

Get the right user engagement

Si se hace de forma incorrecta, la sincronización periódica en segundo plano podría suponer un desperdicio de recursos de los usuarios. Antes de lanzarlo, Chrome lo sometió a un período de prueba para asegurarse de que era correcto. Esta sección explica algunas de las decisiones de diseño que tomó Chrome para que esta función be lo más útil posible.

The first design decision Chrome made is that a web app can only use periodic background syncing after someone has installed it on their device and launched it as a separate app. Periodic background syncing is not available in the context of a normal tab in Chrome.

Also, since Chrome doesn't want unused or infrequently used web apps to consume battery or data for free, Chrome designed a regular background sync so developers have to earn it by providing value to their users. . Specifically, Chrome is using a site interaction score
(chrome://site-engagement/) to determine whether and how often to perform periodic background syncs for a given web application. In other words, a periodicsync The event no se activará en absoluto a menos que la puntuación de participación sea mayor que cero, y su valor afecta la frecuencia con la que
periodicsync event fires. This ensures that the only apps that sync in the background are the ones you are actively using.

La sincronización periódica en segundo plano comparte algunas similitudes con las API y las prácticas existentes en plataformas populares. Por ejemplo, la sincronización en segundo plano única y las notificaciones automáticas permiten que la lógica de una aplicación web viva un poco más (a través de su trabajador de servicio) después de que una persona ha cerrado la página. En la mayoría de las plataformas, es común que las persons hayan instalado aplicaciones que acceden periódicamente a la red en segundo plano para brindar una mejor user experience para actualizaciones críticas, obtención previa de contenido, sincronización de datos, etc. De manera similar, la sincronización periódica en segundo plano también extiende la vida útil de la lógica de una aplicación web para que se ejecute en períodos regulares durante lo que pueden ser unos pocos minutos a la vez.

If he browser permitiera que esto ocurriera con frecuencia y sin restricciones, podría generar algunos problemas de privacidad. Así es como Chrome ha abordado este riesgo de sincronización periódica en segundo plano:

  • Background sync activity only occurs on a network that the device has previously connected to. Chrome recommends connecting only to networks operated by trusted parties.
  • Como ocurre con todas las comunicaciones por Internet, la sincronización periódica en segundo plano revela las direcciones IP del client, el servidor con el que está hablando y el nombre del servidor. Para reducir esta exposición aproximadamente a lo que sería si la aplicación solo se sincronizara cuando estuviera en primer plano, el navegador limita la frecuencia de las sincronizaciones en segundo plano de una aplicación para alinearse con la frecuencia con la que la persona usa esa aplicación. Si la persona deja de interactuar con frecuencia con la aplicación, la sincronización periódica en segundo plano dejará de activarse. Esta es una mejora neta sobre el status quo en las aplicaciones nativas.

When can it be used?

The rules of use vary by browser. To summarize the above, Chrome imposes the following requirements on periodic background syncing:

  • A particular user engagement score.
  • Presence of a previously used network.

The developers do not control the timing of the syncs. The sync frequency will align with how often the app is used. (Note that native apps currently don't do this.) It also takes into account the power and connectivity status of the device.

When should it be used?

When your service worker wakes up to drive a periodicsync event, you have the
chance to request data, but not the obligation to do it. When handling the event, you need to take into account network conditions and available storage, and in response download different amounts of data. You can use the following resources to help:

Permissions

After the service worker is installed, use the Permissions API to consult periodic-background-sync. You can do this from a window or from a service worker context.

const status = await navigator.permissions.query({
yam: 'periodic-background-sync',
});
if (status.state === 'granted') {
} else {
}

Recording a periodic sync

As already mentioned, periodic background synchronization requires a service worker. Retrieve a PeriodicSyncManager using ServiceWorkerRegistration.periodicSync and call
register () in that. The record requires both a tag and a minimum sync interval (minInterval). The tag identifies the logged sync so that multiple syncs can be logged. In the following example, the tag name is
'content-sync' and the minInterval it's one day.

const registration = await navigator.serviceWorker.ready;
if ('periodicSync' in registration) {
try {
await registration.periodicSync.register('content-sync', {

minInterval: 24 * 60 * 60 * 1000,
});
} catch (error) {

}
}

Verifying a record

Call periodicSync.getTags () para recuperar una serie de etiquetas de registro. El siguiente ejemplo utiliza nombres de etiquetas para confirmar que la actualización de la cache está activa para evitar la actualización de nuevo.

const registration = await navigator.serviceWorker.ready;
if ('periodicSync' in registration) {
const tags = await registration.periodicSync.getTags();

if (!tags.includes('content-sync')) {
updateContentOnPageLoad();
}
} else {

updateContentOnPageLoad();
}

You can also use getTags () to display a list of active logs on the configuration page of your web application so that users can enable or disable specific types of updates.

Respond to a recurring background sync event

To respond to a recurring background sync event, add a periodicsync event handler to your service worker. the event The object passed to him will contain a
tag parameter that matches the value used during registration. For example, if a periodic background sync was recorded with the name 'content-sync', soon
event.tag will be 'content-sync'.

self.addEventListener('periodicsync', (event) => {
if (event.tag === 'content-sync') {
event.waitUntil(syncContent());
}
});

Unregister a sync

To end a registered sync, call periodicSync.unregister () with the name of the sync you want to unregister.

const registration = await navigator.serviceWorker.ready;
if ('periodicSync' in registration) {
await registration.periodicSync.unregister('content-sync');
}

Interfaces

Here's a quick rundown of the interfaces provided by the Background Periodic Sync API.

  • PeriodicSyncEvent. Passed to ServiceWorkerGlobalScope.onperiodicsync event handler at the time the browser chooses.
  • PeriodicSyncManager. Records and unregisters recurring syncs and provides labels for logged syncs. Retrieve an instance of this class from the ServiceWorkerRegistration.periodicSync` property.
  • ServiceWorkerGlobalScope.onperiodicsync. Register a handler to receive the PeriodicSyncEvent.
  • ServiceWorkerRegistration.periodicSync. Returns a reference to the PeriodicSyncManager.

Example

Updating content

El siguiente ejemplo utiliza la sincronización periódica en segundo plano para descargar y almacenar en caché artículos actualizados para un sitio de noticias o Blog. Observe el nombre de la etiqueta, que indica el tipo de sincronización que es ('update-articles'). The call to updateArticles () is wrapped in event.waitUntil () so that the service worker does not finish before the items are unloaded and stored.

async function updateArticles() {
const articlesCache = await caches.open('articles');
await articlesCache.add('/api/articles');
}

self.addEventListener('periodicsync', (event) => {
if (event.tag === 'update-articles') {
event.waitUntil(updateArticles());
}
});

Add periodic background sync to an existing web app

This set of changes were needed to add periodic background synchronization to a Existing PWA. This example includes a number of useful log statements that describe the state of periodic background synchronization in the web application.

Depuration

It can be challenging to get an end-to-end view of the periodic background sync while doing a local test. Information about active logs, approximate sync intervals, and past sync event logs provide valuable context when debugging the behavior of your web application. Fortunately, you can find all of that information via an experimental feature in Chrome DevTools.

Periodic debugging of background sync is enabled in Chrome 81 and later.

Local activity record

the Periodic synchronization in the background The DevTools section is organized around milestones in the periodic background sync lifecycle: sign up to sync, sync in the background, and unregister. For information on these events, click Start recording.

1-record-7229790

The record button in DevTools

Durante la grabación, las entradas aparecerán en DevTools correspondientes a los eventos, con el contexto y los metadata registrados para cada uno.

2-record-result-2743260

An example of recorded periodic background sync data

After you enable recording once, it will remain enabled for up to three days, allowing DevTools to capture local debugging information about background syncs that could take place, even hours in the future.

Simulating events

While logging activity in the background can be helpful, there are times when you'll want to test your periodicsync handler immediately, without waiting for an event to fire at its normal cadence.

You can do it through the Service workers inside the Application panel in Chrome DevTools. the Periodic synchronization The field allows you to provide a label for you to use the event and trigger it as many times as you like.

Manually activating a periodicsync event requires Chrome 81 or later.

3-sw-panel-6598906

Starting with Chrome 81, you will see a Periodic synchronization in the background section in DevTools Request panel.

7-panel-6273996