1
+ const message = document . getElementById ( 'message' )
2
+
1
3
navigator . serviceWorker
2
4
. register ( `${ window . location . pathname } service-worker.js` )
3
5
. then ( registration => {
4
- console . log ( ' Service worker successfully registered.' ) ;
6
+ message . innerHTML += '<p> Service worker successfully registered</p>'
5
7
} )
6
8
. catch ( err => {
7
- console . error ( 'Unable to register service worker.' , err ) ;
8
- } ) ;
9
-
10
- const button = document . querySelector ( 'button' ) ;
9
+ message . innerHTML += `<p>Unable to register service worker - ${ err } </p>`
10
+ } )
11
11
12
- button . addEventListener ( 'click' , event => {
12
+ const request = document . getElementById ( 'request' )
13
+ const subscribe = document . getElementById ( 'subscribe' )
13
14
15
+ request . addEventListener ( 'click' , event => {
14
16
Notification . requestPermission ( )
15
17
. then ( permission => {
18
+ message . innerHTML += `<p>Permission ${ permission } </p>`
19
+ } )
20
+ } ) ;
16
21
17
- navigator . serviceWorker . ready . then ( registration => {
18
-
19
- console . log ( 'Service worker is active' ) ;
22
+ subscribe . addEventListener ( 'click' , event => {
23
+ navigator . serviceWorker . ready
24
+ . then ( registration => {
20
25
21
- registration . pushManager . subscribe ( {
22
- userVisibleOnly : true ,
23
- applicationServerKey : 'some_public_key'
24
- } ) . then ( pushSubscription => {
25
- console . log ( 'Received PushSubscription: ' , JSON . stringify ( pushSubscription ) ) ;
26
- } ) ;
27
- } ) ;
26
+ registration . pushManager . subscribe ( {
27
+ userVisibleOnly : true ,
28
+ applicationServerKey : 'BDntLA3k5K1tsrFOXXAuS_9Ey30jxy-R2CAosC2DOQnTs8LpQGxpTEx3AcPXinVYFFpJI6tT_RJC8pHgUsdbhOk'
28
29
} )
29
- } ) ;
30
+ . then ( pushSubscription => {
31
+ message . innerHTML += `<p>Received PushSubscription:</p>`
32
+ message . innerHTML += `<p>${ JSON . stringify ( pushSubscription ) } </p>`
33
+ } )
34
+ . catch ( err => {
35
+ registration . pushManager . getSubscription ( ) . then ( subscription => {
36
+ if ( subscription !== null ) {
37
+ subscription
38
+ . unsubscribe ( )
39
+ . then ( successful => {
40
+ message . innerHTML += '<p>Unsubscribed from existing subscription, please subscribe again</p>'
41
+ } )
42
+ . catch ( err => {
43
+ message . innerHTML += `<p>Failed to unsubscribe from existing subscription - ${ err } </p>`
44
+ } )
45
+ } else {
46
+ message . innerHTML += '<p>No subscription found</p>'
47
+ }
48
+ } )
49
+ } )
50
+ } )
51
+ } )
0 commit comments