PushSubscription: getKey() 方法

Baseline 已廣泛支援

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

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

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

PushSubscription 介面的 getKey() 方法返回一個 ArrayBuffer,它代表一個客戶端公鑰,該公鑰可以傳送到伺服器並用於加密推送訊息資料。

語法

js
getKey(name)

引數

name

一個字串,表示用於生成客戶端金鑰的加密方法。該值可以是

p256dh

P-256 曲線(即 NIST secp256r1 橢圓曲線)上的橢圓曲線 Diffie–Hellman 公鑰。生成的金鑰是 ANSI X9.62 格式的未壓縮點。

auth

一個身份驗證金鑰,如Web 推送訊息加密中所述。

返回值

如果找不到公鑰,則返回一個 ArrayBuffernull

示例

js
reg.pushManager.getSubscription().then((subscription) => {
  // Enable any UI which subscribes / unsubscribes from
  // push messages.

  subBtn.disabled = false;

  if (!subscription) {
    console.log("Not yet subscribed to Push");
    // We aren't subscribed to push, so set UI
    // to allow the user to enable push
    return;
  }

  // Set your UI to show they have subscribed for
  // push messages
  subBtn.textContent = "Unsubscribe from Push Messaging";
  isPushEnabled = true;

  // initialize status, which includes setting UI elements for subscribed status
  // and updating Subscribers list via push
  const endpoint = subscription.endpoint;
  const key = subscription.getKey("p256dh");
  const auth = subscription.getKey("auth");

  // …
});

規範

規範
推送 API
# dom-pushsubscription-getkey

瀏覽器相容性