Esta tradução está incompleta. Por favor, ajude a traduzir este artigo do Inglês.

Os service workers atuam essencialmente como servidores de proxy que ficam entre as aplicações da Web, e o navegador e a rede (quando disponível). Eles são destinados para (entre outras coisas) ativar a criação de experiências efetivas, intercetar pedidos de rede e tomando medidas adequadas com base na disponibilidade da rede e na atualização dos ativos no servidor. Eles também irão permitir o acesso para solicitar notificações e sincronizar as APIs em segundo plano.

Conceitos e utilização do service worker

A service worker is an event-driven worker registered against an origin and a path. It takes the form of a JavaScript file that can control the web page/site it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion to give you complete control over how your app behaves in certain situations (the most obvious one being when the network is not available.)

A service worker is run in a worker context: it therefore has no DOM access, and runs on a different thread to the main JavaScript that powers your app, so it is not blocking. It is designed to be fully async; as a consequence, APIs such as synchronous XHR and localStorage can't be used inside a service worker.

Service workers only run over HTTPS, for security reasons. Having modified network requests wide open to man in the middle attacks would be really bad. In Firefox, Service Worker APIs are also hidden and cannot be used when the user is in private browsing mode.

Nota: Service Workers win over previous attempts in this area such as AppCache because they don't make assumptions about what you are trying to do and then break when those assumptions are not exactly right; you have granular control over everything.

Nota: Service workers make heavy use of promises, as generally they will wait for responses to come through, after which they will respond with a success or failure action. The promises architecture is ideal for this.

Registo

A service worker is first registered using the ServiceWorkerContainer.register() method. If successful, your service worker will be downloaded to the client and attempt installation/activation (see below) for URLs accessed by the user inside the whole origin, or inside a subset specified by you.

Transferir, instalar e ativar

Neste ponto, o seu service worker observará o seguinte ciclo vital:

  1. Transferir
  2. Instalar
  3. Ativar

The service worker is immediately downloaded when a user first accesses a service worker–controlled site/page.

After that it is downloaded every 24 hours or so. It may be downloaded more frequently, but it must be downloaded every 24h to prevent bad scripts from being annoying for too long.

Installation is attempted when the downloaded file is found to be new — either different to an existing service worker (byte-wise compared), or the first service worker encountered for this page/site.

If this is the first time a service worker has been made available, installation is attempted, then after a successful installation it is activated.

If there is an existing service worker available, the new version is installed in the background, but not yet activated — at this point it is called the worker in waiting. It is only activated when there are no longer any pages loaded that are still using the old service worker. As soon as there are no more such pages still loaded, the new service worker activates (becoming the active worker).  Activation can happen sooner using ServiceWorkerGlobalScope.skipWaiting() and existing pages can be claimed by the active worker using Clients.claim().

You can listen out for the InstallEvent; a standard action is to prepare your service worker for usage when this fires, for example by creating a cache using the built in storage API, and placing assets inside it that you'll want for running your app offline.

There is also an activate event. The point where this event fires is generally a good time to clean up old caches and other things associated with the previous version of your service worker.

Your service worker can respond to requests using the FetchEvent event. You can modify the response to these requests in any way you want, using the FetchEvent.respondWith method.

Nota: Because oninstall/onactivate could take a while to complete, the service worker spec provides a waitUntil method that, when called oninstall or onactivate, passes a promise. Functional events are not dispatched to the service worker until the promise successfully resolves.

For a complete tutorial to show how to build up your first basic example, read Using Service Workers.

Outras ideas de casos de utilização

Service workers are also intended to be used for such things as:

  • Background data synchronization
  • Responding to resource requests from other origins
  • Receiving centralized updates to expensive-to-calculate data such as geolocation or gyroscope, so multiple pages can make use of one set of data
  • Client-side compiling and dependency management of CoffeeScript, less, CJS/AMD modules, etc. for dev purposes
  • Hooks for background services
  • Custom templating based on certain URL patterns
  • Performance enhancements, for example pre-fetching resources that the user is likely to need in the near future, such as the next few pictures in a photo album.

In the future, service workers will be able to do a number of other useful things for the web platform that will bring it closer towards native app viability. Interestingly, other specifications can and will start to make use of the service worker context, for example:

  • Background synchronization: Start up a service worker even when no users are at the site, so caches can be updated, etc.
  • Reacting to push messages: Start up a service worker to send users a message to tell them new content is available.
  • Reacting to a particular time & date
  • Entering a geo-fence

Interfaces

Cache
Represents the storage for Request / Response object pairs that are cached as part of the ServiceWorker life cycle.
CacheStorage
Represents the storage for Cache objects. It provides a master directory of all the named caches that a ServiceWorker can access and maintains a mapping of string names to corresponding Cache objects.
Client
Represents the scope of a service worker client. A service worker client is either a document in a browser context or a SharedWorker, which is controlled by an active worker.
Clients
Represents a container for a list of Client objects; the main way to access the active service worker clients at the current origin.
ExtendableEvent
Extends the lifetime of the install and activate events dispatched on the ServiceWorkerGlobalScope as part of the service worker lifecycle. This ensures that any functional events (like FetchEvent ) are not dispatched to the ServiceWorker until it upgrades database schemas, deletes outdated cache entries, etc.
ExtendableMessageEvent
The event object of a message event fired on a service worker (when a channel message is received on the ServiceWorkerGlobalScope from another context) — extends the lifetime of such events.
FetchEvent
The parameter passed into the ServiceWorkerGlobalScope.onfetch handler, FetchEvent represents a fetch action that is dispatched on the ServiceWorkerGlobalScope of a ServiceWorker. It contains information about the request and resulting response, and provides the FetchEvent.respondWith() method, which allows us to provide an arbitrary response back to the controlled page.
InstallEvent
The parameter passed into the oninstall handler, the InstallEvent interface represents an install action that is dispatched on the ServiceWorkerGlobalScope of a ServiceWorker. As a child of ExtendableEvent, it ensures that functional events such as FetchEvent are not dispatched during installation. 
NavigationPreloadManager
Provides methods for managing the preloading of resources with a service worker. 
Navigator.serviceWorker
Returns a ServiceWorkerContainer object, which provides access to registration, removal, upgrade, and communication with the ServiceWorker objects for the associated document.
NotificationEvent
The parameter passed into the onnotificationclick handler, the NotificationEvent interface represents a notification click event that is dispatched on the ServiceWorkerGlobalScope of a ServiceWorker.
ServiceWorker
Represents a service worker. Multiple browsing contexts (e.g. pages, workers, etc.) can be associated with the same ServiceWorker object.
ServiceWorkerContainer
Provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations.
ServiceWorkerGlobalScope
Represents the global execution context of a service worker.
ServiceWorkerMessageEvent
Represents a message sent to a ServiceWorkerGlobalScope. Note that this interface is deprecated in modern browsers. Service worker messages will now use the MessageEvent interface, for consistency with other web messaging features.
ServiceWorkerRegistration
Represents a service worker registration.
ServiceWorkerState
Associated with its ServiceWorker's state.
SyncEvent

The SyncEvent interface represents a sync action that is dispatched on the ServiceWorkerGlobalScope of a ServiceWorker. 

SyncManager
Provides an interface for registering and listing sync registrations.
WindowClient
Represents the scope of a service worker client that is a document in a browser context, controlled by an active worker. This is a special type of Client object, with some additional methods and properties available.

Especificações

Specification Status Comment
Service Workers Editor's Draft Initial definition.

Compatibilidade de navegador

Funcionalidade Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 40 No support[1] 44.0 (44.0)[2] No support 24 No support[3]
install/activate events 40 No support[1] 44.0 (44.0)[2] No support (Yes) No support
fetch event/request/
respondWith()
40 No support[1] 44.0 (44.0)[2] No support No support No support
caches/cache

42

No support[1] 39.0 (39.0)[2] No support No support No support
ServiceWorkerMessageEvent deprecated in favour of MessageEvent

57

No support 55.0 (55.0)[2] No support No support No support
NavigationPreloadManager 59 No support   No support 46 No support
Funcionalidade Android Webview Chrome for Android Edge Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support No support 40 No support[1] 44.0 (44.0) No support (Yes) No support[3]
 install/activate events No support 40 No support[1] 44.0 (44.0) No support (Yes) No support
fetch event/request/
respondWith()
No support 40 No support[1] 44.0 (44.0) No support No support No support
caches/cache No support 40 No support[1] 39.0 (39.0) No support No support No support
ServiceWorkerMessageEvent deprecated in favour of MessageEvent No support

57

No support 55.0 (55.0) No support No support No support
NavigationPreloadManager No support 59 No support No support No support 46 No support

[1] This feature is not supported yet, though it's already in development.

[2] Service workers (and Push) have been disabled in the Firefox 45 & 52 Extended Support Releases (ESR.)

[3] This feature is not supported yet, though it's currently in development.

Consultar também

Etiquetas do documento e contribuidores

 Contribuidores para esta página: mansil
 Última atualização por: mansil,