PushManager: subscribe() 方法

Baseline 已廣泛支援

此功能已成熟,並可在許多裝置和瀏覽器版本上執行。自 2023 年 3 月以來,它已在各種瀏覽器中可用。

安全上下文: 此功能僅在安全上下文(HTTPS)中可用,且支援此功能的瀏覽器數量有限。

注意:此功能在 Web Workers 中可用。

subscribe() 方法是 PushManager 介面的一部分,用於訂閱推送服務。

它返回一個 Promise,該 Promise 解析為一個 PushSubscription 物件,其中包含推送訂閱的詳細資訊。如果當前 service worker 沒有現有的訂閱,則會建立一個新的推送訂閱。

語法

js
subscribe(options)

引數

options 可選

一個包含可選配置引數的物件。它可以包含以下屬性:

userVisibleOnly

一個布林值,指示返回的推送訂閱僅用於對使用者可見的效果的訊息。

applicationServerKey

一個 Base64 編碼的字串或 ArrayBuffer,其中包含一個 ECDSA P-256 公鑰,推送伺服器將使用該公鑰來驗證您的應用程式伺服器。如果指定了此引數,則您的應用程式伺服器傳送的所有訊息都必須使用 VAPID 身份驗證方案,幷包含一個使用相應私鑰簽名的 JWT。此金鑰不是您用於加密資料的 ECDH 金鑰。有關更多資訊,請參閱“使用 VAPID 進行 WebPush”。

注意: 在 Chrome 和 Edge 等某些瀏覽器中,此引數是必需的。如果 userVisibleOnly 未設定為 true,它們將拒絕 Promise。

返回值

一個 Promise,該 Promise 解析為一個 PushSubscription 物件。

示例

js
this.onpush = (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");

// Use serviceWorker.ready to ensure that you can subscribe for push
navigator.serviceWorker.ready.then((serviceWorkerRegistration) => {
  const options = {
    userVisibleOnly: true,
    applicationServerKey,
  };
  serviceWorkerRegistration.pushManager.subscribe(options).then(
    (pushSubscription) => {
      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, the fetch() API.
    },
    (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.error(error);
    },
  );
});

響應使用者操作

subscribe() 呼叫應在響應使用者操作後執行,例如單擊按鈕:

js
btn.addEventListener("click", () => {
  serviceWorkerRegistration.pushManager
    .subscribe(options)
    .then((pushSubscription) => {
      // handle subscription
    });
});

這不僅是最佳實踐——您不應該向使用者傳送他們不同意的通知——而且未來瀏覽器將明確禁止未經使用者操作觸發的通知。例如,Firefox 從 72 版本開始就已經這樣做了。

規範

規範
推送 API
# dom-pushmanager-subscribe

瀏覽器相容性