PushManager: phương thức getSubscription()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2023.

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

Note: This feature is available in Web Workers.

Phương thức PushManager.getSubscription() của giao diện PushManager truy xuất một subscription đẩy hiện có.

Phương thức này trả về một Promise giải quyết thành một đối tượng PushSubscription chứa chi tiết của một subscription hiện có. Nếu không có subscription nào, giá trị giải quyết là null.

Cú pháp

js
getSubscription()

Tham số

Không có.

Giá trị trả về

Một Promise giải quyết thành một đối tượng PushSubscription hoặc null.

Ví dụ

Đoạn mã này được lấy từ một mẫu push messaging và notification. Không có bản demo trực tiếp.

js
// Chúng ta cần đăng ký service worker để kiểm tra subscription
navigator.serviceWorker.ready.then((serviceWorkerRegistration) => {
  // Chúng ta đã có subscription cho push message chưa?
  serviceWorkerRegistration.pushManager
    .getSubscription()
    .then((subscription) => {
      // Bật mọi UI dùng để đăng ký/hủy đăng ký
      // push messages.
      const pushButton = document.querySelector(".js-push-button");
      pushButton.disabled = false;

      if (!subscription) {
        // Chưa đăng ký push, nên hãy cấu hình UI
        // để cho phép người dùng bật push
        return;
      }

      // Đồng bộ máy chủ của bạn với subscriptionId mới nhất
      sendSubscriptionToServer(subscription);

      showCurlCommand(subscription);

      // Đặt UI để cho thấy rằng họ đã đăng ký
      // nhận push messages
      pushButton.textContent = "Disable Push Messages";
      isPushEnabled = true;
    })
    .catch((err) => {
      console.error(`Error during getSubscription(): ${err}`);
    });
});

Thông số kỹ thuật

Specification
Push API
# dom-pushmanager-getsubscription

Tương thích trình duyệt