* Subscribes to Web Push Notifications, * after requesting and receiving user permission. * * @param options An object containing the `serverPublicKey` string. * @returns A Promise that resolves to the new subscription object.
(options: {serverPublicKey: string})
| 228 | * @returns A Promise that resolves to the new subscription object. |
| 229 | */ |
| 230 | requestSubscription(options: {serverPublicKey: string}): Promise<PushSubscription> { |
| 231 | if (!this.sw.isEnabled || this.pushManager === null) { |
| 232 | return Promise.reject(new Error(ERR_SW_NOT_SUPPORTED)); |
| 233 | } |
| 234 | const pushOptions: PushSubscriptionOptionsInit = {userVisibleOnly: true}; |
| 235 | let key = this.decodeBase64(options.serverPublicKey.replace(/_/g, '/').replace(/-/g, '+')); |
| 236 | let applicationServerKey = new Uint8Array(new ArrayBuffer(key.length)); |
| 237 | for (let i = 0; i < key.length; i++) { |
| 238 | applicationServerKey[i] = key.charCodeAt(i); |
| 239 | } |
| 240 | pushOptions.applicationServerKey = applicationServerKey; |
| 241 | |
| 242 | return new Promise((resolve, reject) => { |
| 243 | this.pushManager!.pipe( |
| 244 | switchMap((pm) => pm.subscribe(pushOptions)), |
| 245 | take(1), |
| 246 | ).subscribe({ |
| 247 | next: (sub) => { |
| 248 | this.subscriptionChanges.next(sub); |
| 249 | resolve(sub); |
| 250 | }, |
| 251 | error: reject, |
| 252 | }); |
| 253 | }); |
| 254 | } |
| 255 | |
| 256 | /** |
| 257 | * Unsubscribes from Service Worker push notifications. |