This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

PushManager

Baseline 2023
Newly available

Since ⁨March 2023⁩, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

Примечание: Эта возможность доступна в Web Workers.

Интерфейс PushManager из Push API предоставляет возможность получать уведомления от сторонних серверов, а также запрашивать URL для push уведомлений.

Этот интерфейс доступен через свойство ServiceWorkerRegistration.pushManager.

Примечание: Этот интерфейс заменил функциональность, предлагаемую устаревшим PushRegistrationManager.

Свойства

PushManager.supportedContentEncodings

Возвращает массив со списком возможных алгоритмов кодирования, которые могут быть использованы для шифрования полезной нагрузки пуш-уведомления.

Методы

PushManager.subscribe()

Подписка на пуш сервис. Возвращает промис, который разрешается в PushSubscription объект, содержащий детали новой push подписки.

PushManager.getSubscription()

Извлекает существующую push подписку. Возвращает промис, который разрешается в PushSubscription объект, содержащий детали существующей подписки.

PushManager.permissionState()

Возвращает Promise, который разрешается в состояние доступа текущего PushManager, которое может быть одним из 'granted', 'denied', или 'default'.

Устаревшие методы

PushManager.hasPermission()

Returns a Promise that resolves to the PushPermissionStatus of the requesting webapp, which will be one of granted, denied, or default. Replaced by PushManager.permissionState().

PushManager.register()

Subscribes to a push subscription. Replaced by PushManager.subscribe().

PushManager.registrations()

Retrieves existing push subscriptions. Replaced by PushManager.getSubscription().

PushManager.unregister()

Unregisters and deletes a specified subscription endpoint. In the updated API, a subscription is can be unregistered via the PushSubscription.unsubscribe() method.

Пример

js
this.onpush = function (event) {
  console.log(event.data);
  // From here we can write the data to IndexedDB, send it to any open
  // windows, display a notification, etc.
};

navigator.serviceWorker
  .register("serviceworker.js")
  .then(function (serviceWorkerRegistration) {
    serviceWorkerRegistration.pushManager.subscribe().then(
      function (pushSubscription) {
        console.log(pushSubscription.subscriptionId);
        console.log(pushSubscription.endpoint);
        // The push subscription details needed by the application
        // server are now available, and can be sent to it using,
        // for example, an XMLHttpRequest.
      },
      function (error) {
        // During development it often helps to log errors to the
        // console. In a production environment it might make sense to
        // also report information about errors back to the
        // application server.
        console.log(error);
      },
    );
  });

Спецификации

Specification
Push API
# pushmanager-interface

Совместимость с браузерами

Смотрите также