@angular/service-worker

  • Version 14.0.4
  • Published
  • 410 kB
  • 1 dependency
  • MIT license

Install

npm i @angular/service-worker
yarn add @angular/service-worker
pnpm add @angular/service-worker

Overview

Angular - service worker tooling!

Index

Classes

class ServiceWorkerModule

class ServiceWorkerModule {}

property ɵfac

static ɵfac: i0.ɵɵFactoryDeclaration<ServiceWorkerModule, never>;

    property ɵinj

    static ɵinj: i0.ɵɵInjectorDeclaration<ServiceWorkerModule>;

      property ɵmod

      static ɵmod: i0.ɵɵNgModuleDeclaration<ServiceWorkerModule, never, never, never>;

        method register

        static register: (
        script: string,
        opts?: SwRegistrationOptions
        ) => ModuleWithProviders<ServiceWorkerModule>;
        • Register the given Angular Service Worker script.

          If enabled is set to false in the given options, the module will behave as if service workers are not supported by the browser, and the service worker will not be registered.

        class SwPush

        class SwPush {}
        • Subscribe and listen to [Web Push Notifications](https://developer.mozilla.org/en-US/docs/Web/API/Push_API/Best_Practices) through Angular Service Worker.

          You can inject a SwPush instance into any component or service as a dependency.

          To subscribe, call SwPush.requestSubscription(), which asks the user for permission. The call returns a Promise with a new [PushSubscription](https://developer.mozilla.org/en-US/docs/Web/API/PushSubscription) instance.

          A request is rejected if the user denies permission, or if the browser blocks or does not support the Push API or ServiceWorkers. Check SwPush.isEnabled to confirm status.

          Invoke Push Notifications by pushing a message with the following payload.

          {
          "notification": {
          "actions": NotificationAction[],
          "badge": USVString,
          "body": DOMString,
          "data": any,
          "dir": "auto"|"ltr"|"rtl",
          "icon": USVString,
          "image": USVString,
          "lang": DOMString,
          "renotify": boolean,
          "requireInteraction": boolean,
          "silent": boolean,
          "tag": DOMString,
          "timestamp": DOMTimeStamp,
          "title": DOMString,
          "vibrate": number[]
          }
          }

          Only title is required. See Notification [instance properties](https://developer.mozilla.org/en-US/docs/Web/API/Notification#Instance_properties).

          While the subscription is active, Service Worker listens for [PushEvent](https://developer.mozilla.org/en-US/docs/Web/API/PushEvent) occurrences and creates [Notification](https://developer.mozilla.org/en-US/docs/Web/API/Notification) instances in response.

          Unsubscribe using SwPush.unsubscribe().

          An application can subscribe to SwPush.notificationClicks observable to be notified when a user clicks on a notification. For example:

          You can read more on handling notification clicks in the [Service worker notifications guide](guide/service-worker-notifications).

          See Also

          • [Push Notifications](https://developers.google.com/web/fundamentals/codelabs/push-notifications/)

          • [Angular Push Notifications](https://blog.angular-university.io/angular-push-notifications/)

          • [MDN: Push API](https://developer.mozilla.org/en-US/docs/Web/API/Push_API)

          • [MDN: Notifications API](https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API)

          • [MDN: Web Push API Notifications best practices](https://developer.mozilla.org/en-US/docs/Web/API/Push_API/Best_Practices)

        constructor

        constructor(sw: NgswCommChannel);

          property isEnabled

          readonly isEnabled: boolean;
          • True if the Service Worker is enabled (supported by the browser and enabled via ServiceWorkerModule).

          property messages

          readonly messages: Observable<object>;
          • Emits the payloads of the received push notification messages.

          property notificationClicks

          readonly notificationClicks: Observable<{
          action: string;
          notification: NotificationOptions & { title: string };
          }>;
          • Emits the payloads of the received push notification messages as well as the action the user interacted with. If no action was used the action property contains an empty string ''.

            Note that the notification property does **not** contain a [Notification][Mozilla Notification] object but rather a [NotificationOptions](https://notifications.spec.whatwg.org/#dictdef-notificationoptions) object that also includes the title of the [Notification][Mozilla Notification] object.

            [Mozilla Notification]: https://developer.mozilla.org/en-US/docs/Web/API/Notification

          property ɵfac

          static ɵfac: i0.ɵɵFactoryDeclaration<SwPush, never>;

            property ɵprov

            static ɵprov: i0.ɵɵInjectableDeclaration<SwPush>;

              property subscription

              readonly subscription: Observable<PushSubscription>;
              • Emits the currently active [PushSubscription](https://developer.mozilla.org/en-US/docs/Web/API/PushSubscription) associated to the Service Worker registration or null if there is no subscription.

              method requestSubscription

              requestSubscription: (options: {
              serverPublicKey: string;
              }) => Promise<PushSubscription>;
              • Subscribes to Web Push Notifications, after requesting and receiving user permission.

                Parameter options

                An object containing the serverPublicKey string.

                Returns

                A Promise that resolves to the new subscription object.

              method unsubscribe

              unsubscribe: () => Promise<void>;
              • Unsubscribes from Service Worker push notifications.

                Returns

                A Promise that is resolved when the operation succeeds, or is rejected if there is no active subscription or the unsubscribe operation fails.

              class SwRegistrationOptions

              abstract class SwRegistrationOptions {}
              • Token that can be used to provide options for ServiceWorkerModule outside of ServiceWorkerModule.register().

                You can use this token to define a provider that generates the registration options at runtime, for example via a function call:

              property enabled

              enabled?: boolean;
              • Whether the ServiceWorker will be registered and the related services (such as SwPush and SwUpdate) will attempt to communicate and interact with it.

                Default: true

              property registrationStrategy

              registrationStrategy?: string | (() => Observable<unknown>);
              • Defines the ServiceWorker registration strategy, which determines when it will be registered with the browser.

                The default behavior of registering once the application stabilizes (i.e. as soon as there are no pending micro- and macro-tasks) is designed to register the ServiceWorker as soon as possible but without affecting the application's first time load.

                Still, there might be cases where you want more control over when the ServiceWorker is registered (for example, there might be a long-running timeout or polling interval, preventing the app from stabilizing). The available option are:

                - registerWhenStable:<timeout>: Register as soon as the application stabilizes (no pending micro-/macro-tasks) but no later than <timeout> milliseconds. If the app hasn't stabilized after <timeout> milliseconds (for example, due to a recurrent asynchronous task), the ServiceWorker will be registered anyway. If <timeout> is omitted, the ServiceWorker will only be registered once the app stabilizes. - registerImmediately: Register immediately. - registerWithDelay:<timeout>: Register with a delay of <timeout> milliseconds. For example, use registerWithDelay:5000 to register the ServiceWorker after 5 seconds. If <timeout> is omitted, is defaults to 0, which will register the ServiceWorker as soon as possible but still asynchronously, once all pending micro-tasks are completed. - An [Observable](guide/observables) factory function: A function that returns an Observable. The function will be used at runtime to obtain and subscribe to the Observable and the ServiceWorker will be registered as soon as the first value is emitted.

                Default: 'registerWhenStable:30000'

              property scope

              scope?: string;
              • A URL that defines the ServiceWorker's registration scope; that is, what range of URLs it can control. It will be used when calling [ServiceWorkerContainer#register()](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register).

              class SwUpdate

              class SwUpdate {}
              • Subscribe to update notifications from the Service Worker, trigger update checks, and forcibly activate updates.

                See Also

              constructor

              constructor(sw: NgswCommChannel);

                property activated

                readonly activated: Observable<UpdateActivatedEvent>;
                • Emits an UpdateActivatedEvent event whenever the app has been updated to a new version.

                  Deprecated

                  Use the return value of SwUpdate#activateUpdate instead.

                property available

                readonly available: Observable<UpdateAvailableEvent>;
                • Emits an UpdateAvailableEvent event whenever a new app version is available.

                  Deprecated

                  Use versionUpdates instead.

                  The of behavior available can be rebuild by filtering for the VersionReadyEvent:

                  import {filter, map} from 'rxjs/operators';
                  // ...
                  const updatesAvailable = swUpdate.versionUpdates.pipe(
                  filter((evt): evt is VersionReadyEvent => evt.type === 'VERSION_READY'),
                  map(evt => ({
                  type: 'UPDATE_AVAILABLE',
                  current: evt.currentVersion,
                  available: evt.latestVersion,
                  })));

                property isEnabled

                readonly isEnabled: boolean;
                • True if the Service Worker is enabled (supported by the browser and enabled via ServiceWorkerModule).

                property ɵfac

                static ɵfac: i0.ɵɵFactoryDeclaration<SwUpdate, never>;

                  property ɵprov

                  static ɵprov: i0.ɵɵInjectableDeclaration<SwUpdate>;

                    property unrecoverable

                    readonly unrecoverable: Observable<UnrecoverableStateEvent>;
                    • Emits an UnrecoverableStateEvent event whenever the version of the app used by the service worker to serve this client is in a broken state that cannot be recovered from without a full page reload.

                    property versionUpdates

                    readonly versionUpdates: Observable<VersionEvent>;
                    • Emits a VersionDetectedEvent event whenever a new version is detected on the server.

                      Emits a VersionInstallationFailedEvent event whenever checking for or downloading a new version fails.

                      Emits a VersionReadyEvent event whenever a new version has been downloaded and is ready for activation.

                    method activateUpdate

                    activateUpdate: () => Promise<boolean>;
                    • Updates the current client (i.e. browser tab) to the latest version that is ready for activation.

                      Returns

                      a promise that - resolves to true if an update was activated successfully - resolves to false if no update was available (for example, the client was already on the latest version). - rejects if any error occurs

                    method checkForUpdate

                    checkForUpdate: () => Promise<boolean>;
                    • Checks for an update and waits until the new version is downloaded from the server and ready for activation.

                      Returns

                      a promise that - resolves to true if a new version was found and is ready to be activated. - resolves to false if no new version was found - rejects if any error occurs

                    Interfaces

                    interface UnrecoverableStateEvent

                    interface UnrecoverableStateEvent {}
                    • An event emitted when the version of the app used by the service worker to serve this client is in a broken state that cannot be recovered from and a full page reload is required.

                      For example, the service worker may not be able to retrieve a required resource, neither from the cache nor from the server. This could happen if a new version is deployed to the server and the service worker cache has been partially cleaned by the browser, removing some files of a previous app version but not all.

                      See Also

                    property reason

                    reason: string;

                      property type

                      type: 'UNRECOVERABLE_STATE';

                        interface UpdateActivatedEvent

                        interface UpdateActivatedEvent {}
                        • An event emitted when a new version of the app has been downloaded and activated.

                          See Also

                          Deprecated

                          This event is only emitted by the deprecated SwUpdate#activated. Use the return value of SwUpdate#activateUpdate instead.

                        property current

                        current: {
                        hash: string;
                        appData?: Object;
                        };

                          property previous

                          previous?: {
                          hash: string;
                          appData?: Object;
                          };

                            property type

                            type: 'UPDATE_ACTIVATED';

                              interface UpdateAvailableEvent

                              interface UpdateAvailableEvent {}

                              property available

                              available: {
                              hash: string;
                              appData?: Object;
                              };

                                property current

                                current: {
                                hash: string;
                                appData?: Object;
                                };

                                  property type

                                  type: 'UPDATE_AVAILABLE';

                                    interface VersionDetectedEvent

                                    interface VersionDetectedEvent {}
                                    • An event emitted when the service worker has detected a new version of the app on the server and is about to start downloading it.

                                      See Also

                                    property type

                                    type: 'VERSION_DETECTED';

                                      property version

                                      version: {
                                      hash: string;
                                      appData?: object;
                                      };

                                        interface VersionInstallationFailedEvent

                                        interface VersionInstallationFailedEvent {}
                                        • An event emitted when the installation of a new version failed. It may be used for logging/monitoring purposes.

                                          See Also

                                        property error

                                        error: string;

                                          property type

                                          type: 'VERSION_INSTALLATION_FAILED';

                                            property version

                                            version: {
                                            hash: string;
                                            appData?: object;
                                            };

                                              interface VersionReadyEvent

                                              interface VersionReadyEvent {}
                                              • An event emitted when a new version of the app is available.

                                                See Also

                                              property currentVersion

                                              currentVersion: {
                                              hash: string;
                                              appData?: object;
                                              };

                                                property latestVersion

                                                latestVersion: {
                                                hash: string;
                                                appData?: object;
                                                };

                                                  property type

                                                  type: 'VERSION_READY';

                                                    Type Aliases

                                                    type VersionEvent

                                                    type VersionEvent =
                                                    | VersionDetectedEvent
                                                    | VersionInstallationFailedEvent
                                                    | VersionReadyEvent
                                                    | NoNewVersionDetectedEvent;
                                                    • A union of all event types that can be emitted by .

                                                    Package Files (1)

                                                    Dependencies (1)

                                                    Dev Dependencies (0)

                                                    No dev dependencies.

                                                    Peer Dependencies (2)

                                                    Badge

                                                    To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                                    You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@angular/service-worker.

                                                    • Markdown
                                                      [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@angular/service-worker)
                                                    • HTML
                                                      <a href="https://www.jsdocs.io/package/@angular/service-worker"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>