@@ -70,14 +70,16 @@ export abstract class BaseController
70
70
this . tokenDetailsModel = new TokenDetailsModel ( services ) ;
71
71
}
72
72
73
- async getToken ( ) : Promise < string | null > {
74
- // Check with permissions
75
- const currentPermission = this . getNotificationPermission_ ( ) ;
76
- if ( currentPermission === 'denied' ) {
73
+ async getToken ( ) : Promise < string > {
74
+ // Check notification permission.
75
+ let permission = this . getNotificationPermission ( ) ;
76
+ if ( permission === 'default' ) {
77
+ // The user hasn't allowed or denied notifications yet. Ask them.
78
+ permission = await this . requestNotificationPermission ( ) ;
79
+ }
80
+
81
+ if ( permission !== 'granted' ) {
77
82
throw errorFactory . create ( ErrorCode . NOTIFICATIONS_BLOCKED ) ;
78
- } else if ( currentPermission !== 'granted' ) {
79
- // We must wait for permission to be granted
80
- return null ;
81
83
}
82
84
83
85
const swReg = await this . getSWRegistration_ ( ) ;
@@ -327,10 +329,25 @@ export abstract class BaseController
327
329
/**
328
330
* Returns the current Notification Permission state.
329
331
*/
330
- getNotificationPermission_ ( ) : NotificationPermission {
332
+ private getNotificationPermission ( ) : NotificationPermission {
331
333
return Notification . permission ;
332
334
}
333
335
336
+ /**
337
+ * Requests notification permission from the user.
338
+ */
339
+ private async requestNotificationPermission ( ) : Promise <
340
+ NotificationPermission
341
+ > {
342
+ if ( ! Notification . requestPermission ) {
343
+ // Notification.requestPermission() is not available in service workers.
344
+ // Return the current permission.
345
+ return Notification . permission ;
346
+ }
347
+
348
+ return Notification . requestPermission ( ) ;
349
+ }
350
+
334
351
getTokenDetailsModel ( ) : TokenDetailsModel {
335
352
return this . tokenDetailsModel ;
336
353
}
0 commit comments