Skip to content

Commit 0e34d80

Browse files
committed
Display notification only if tab closed
1 parent 88a2ef8 commit 0e34d80

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

client/index.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff 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

index.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff 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>

service-worker.js

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,26 @@ self.addEventListener('notificationclick', event => {
1616
.then(notifications => notifications.forEach(notification => notification.close()));
1717
});
1818

19+
let counter = 0;
1920
self.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+
}

0 commit comments

Comments
 (0)