File tree Expand file tree Collapse file tree 3 files changed +23
-2
lines changed Expand file tree Collapse file tree 3 files changed +23
-2
lines changed Original file line number Diff line number Diff line change @@ -2,8 +2,13 @@ const client = (() => {
22 let serviceWorkerRegObj ;
33 const notificationButton = document . getElementById ( 'btn-notify' ) ;
44 const pushButton = document . getElementById ( 'btn-push' ) ;
5+ const notificationContainer = document . getElementById ( 'push-notification' ) ;
56 let isUserSubscribed = false ;
67
8+ const notifyInApp = ( message ) => {
9+ notificationContainer . innerText = message ;
10+ } ;
11+
712 const showNotificationButton = ( ) => {
813 notificationButton . style . display = 'inline-block' ;
914 notificationButton . addEventListener ( 'click' , showNotification ) ;
@@ -66,7 +71,9 @@ const client = (() => {
6671 } else {
6772 enablePushNotificationButton ( ) ;
6873 }
69- } )
74+ } ) ;
75+
76+ navigator . serviceWorker . addEventListener ( 'message' , event => notifyInApp ( event . data ) )
7077 } ) ;
7178 } ;
7279
Original file line number Diff line number Diff line change @@ -15,6 +15,7 @@ <h1>Web Push Notifications</h1>
1515 < button id ="btn-notify " class ="notification-btn "> SEND NOTIFICATION</ button >
1616 < button id ="btn-push " class ="push-btn "> ENABLE PUSH NOTIFICATIONS</ button >
1717
18+ < div id ="push-notification "> </ div >
1819< script src ="client/index.js "> </ script >
1920</ main >
2021</ body >
Original file line number Diff line number Diff line change @@ -16,13 +16,26 @@ self.addEventListener('notificationclick', event => {
1616 . then ( notifications => notifications . forEach ( notification => notification . close ( ) ) ) ;
1717} ) ;
1818
19+ let counter = 0 ;
1920self . addEventListener ( 'push' , event => {
2021 const data = event . data . text ( ) ;
2122 const options = {
2223 body : data
2324 } ;
2425
2526 event . waitUntil (
26- self . registration . showNotification ( 'Server Push' , options )
27+ self . clients . matchAll ( )
28+ . then ( clientList => {
29+ console . log ( clientList ) ;
30+ if ( isTabOutOfFocus ( clientList ) ) {
31+ self . registration . showNotification ( 'Server Push' , options ) ;
32+ } else {
33+ clientList [ 0 ] . postMessage ( `Server Push #${ counter ++ } ` ) ;
34+ }
35+ } )
2736 ) ;
2837} ) ;
38+
39+ function isTabOutOfFocus ( clients ) {
40+ return clients . length === 0 ;
41+ }
You can’t perform that action at this time.
0 commit comments