PushManager: subscribe() 方法
注意:此功能在 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 | 
浏览器兼容性
加载中…