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

浏览器兼容性