1+ const message = document . getElementById ( 'message' )
2+
13navigator . serviceWorker
24 . register ( `${ window . location . pathname } service-worker.js` )
35 . then ( registration => {
4- console . log ( ' Service worker successfully registered.' ) ;
6+ message . innerHTML += '<p> Service worker successfully registered</p>'
57 } )
68 . 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+ } )
1111
12- button . addEventListener ( 'click' , event => {
12+ const request = document . getElementById ( 'request' )
13+ const subscribe = document . getElementById ( 'subscribe' )
1314
15+ request . addEventListener ( 'click' , event => {
1416 Notification . requestPermission ( )
1517 . then ( permission => {
18+ message . innerHTML += `<p>Permission ${ permission } </p>`
19+ } )
20+ } ) ;
1621
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 => {
2025
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'
2829 } )
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