Skip to content

Commit 61f3767

Browse files
committed
Show a notification via service worker
1 parent 4e48b0e commit 61f3767

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

client/index.js

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,16 @@
11
const client = (() => {
22
let serviceWorkerRegObj;
3+
const notificationButton = document.getElementById('btn-notify');
4+
5+
const showNotificationButton = () => {
6+
notificationButton.style.display = 'inline-block';
7+
notificationButton.addEventListener('click', showNotification);
8+
};
9+
10+
const showNotification = () => {
11+
navigator.serviceWorker.getRegistration()
12+
.then(registration => registration.showNotification('My First Notification'));
13+
};
314

415
const checkNotificationSupport = () => {
516
if(!('Notification' in window)) {
@@ -8,7 +19,7 @@ const client = (() => {
819

920
console.log("The browser supports notifications!")
1021
return Promise.resolve();
11-
}
22+
};
1223

1324
const registerServiceWorker = () => {
1425
if(!('serviceWorker') in navigator) {
@@ -19,14 +30,15 @@ const client = (() => {
1930
.then(regObj => {
2031
console.log('Service worker is registered successfully!');
2132
serviceWorkerRegObj = regObj;
33+
showNotificationButton();
2234
});
23-
}
35+
};
2436

2537
const requestNotificationPermissions = () => {
2638
return Notification.requestPermission(status => {
2739
console.log('Notification Permission Status:', status);
2840
});
29-
}
41+
};
3042

3143
checkNotificationSupport()
3244
.then(registerServiceWorker)

index.html

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,16 @@
33
<head>
44
<meta charset="UTF-8">
55
<title>Web Push Notifications</title>
6+
<style>
7+
.notification-btn {
8+
display: none;
9+
}
10+
</style>
611
</head>
712
<body>
813
<main>
914
<h1>Web Push Notifications</h1>
15+
<button id="btn-notify" class="notification-btn">SEND NOTIFICATION</button>
1016

1117
<script src="client/index.js"></script>
1218
</main>

0 commit comments

Comments
 (0)