ServiceWorkerContainer.register()

Experimental

Esta es una tecnolog铆a experimental
Comprueba la Tabla de compabilidad de navegadores cuidadosamente antes de usarla en producci贸n.

El m茅todo register()de la interfaz ServiceWorkerContainer crea o actualiza un ServiceWorkerRegistration para un scriptURL. dado

Si tiene 茅xito, el registro de un "service worker" relaciona la URL del script proporcionada con un 谩mbito, que posteriormente se utiliza para la coincidencia de navegaci贸n. Puede llamar a este m茅todo incondicionalmente desde la p谩gina controlada. Es decir, no necesita verificar primero si hay un registro activo.

Existe una confusi贸n frecuente en torno al significado y uso del alcance. Dado que un trabajador de servicio no puede tener un alcance m谩s amplio que su propia ubicaci贸n, solo use la opci贸n de 谩mbito cuando necesite un alcance que sea m谩s estrecho que el predeterminado.

Sintaxis

ServiceWorkerContainer.register(scriptURL, options)
  .then(function(ServiceWorkerRegistration) { ... });

Par谩metros

scriptURL
La URL del script de trabajador de servicio.
options Optional
Un objeto que contiene opciones de registro. Las opciones disponibles actualmente son:
  • alcance: USVString (en-US) representa una URL que define el alcance de registro de un "service worker"; es decir, qu茅 rango de URL puede controlar un "service worker". Esto es generalmente una URL relativa. El valor predeterminado es la URL que obtendr铆a si resolviera './' utilizando la ubicaci贸n de la p谩gina web como base. No es, como se cree com煤nmente, relativo a la ubicaci贸n del "service worker". Vea la secci贸n de Ejemplos para m谩s informaci贸n sobre c贸mo funciona.

Valor retornado

A Promise (en-US) that resolves with a ServiceWorkerRegistration object.

Ejemplos

The examples described here should be taken together to get a better understanding of how service workers scope applies to a page.

The following example uses the default value of scope (by omitting it). The service worker in this case will control example.com/index.html as well as pages underneath it, like example.com/product/description.html.

if ('serviceWorker' in navigator) {
  // Register a service worker hosted at the root of the
  // site using the default scope.
  navigator.serviceWorker.register('/sw.js').then(function(registration) {
    console.log('Service worker registration succeeded:', registration);
  }).catch(function(error) {
    console.log('Service worker registration failed:', error);
  });
} else {
  console.log('Service workers are not supported.');
}

The following code, if included in a page at the root of a site, would apply to exactly the same pages as the example above. Remember the scope, when included, uses the page's location as its base. Alternatively, if this code were included in a page at example.com/product/description.html, the scope of './' would mean that the service worker only applies to resources under example.com/product. If I needed to register a service worker on example.com/product/description.html that applied to all of example.com, I would leave off the scope as above.

if ('serviceWorker' in navigator) {
  // Register a service worker hosted at the root of the
  // site using a more restrictive scope.
  navigator.serviceWorker.register('/sw.js', {scope: './'}).then(function(registration) {
    console.log('Service worker registration succeeded:', registration);
  }).catch(function(error) {
    console.log('Service worker registration failed:', error);
  });
} else {
  console.log('Service workers are not supported.');
}

Specifications

Specification Status Comment
Service Workers
La definici贸n de 'ServiceWorkerContainer' en esta especificaci贸n.
Working Draft Initial definition.

Browser compatibility

BCD tables only load in the browser