-
Notifications
You must be signed in to change notification settings - Fork 0
/
page.tsx
71 lines (63 loc) · 1.96 KB
/
page.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
'use client';
import { useEffect, useState } from 'react';
import { Button } from '../../components/ui/button';
import { checkSupport } from './client-helpers';
const registerSW = async () => {
const registration = await navigator.serviceWorker.register('sw.js');
return registration;
};
const unregisterSW = async () => {
const registration = await navigator.serviceWorker.getRegistration();
if (registration) {
registration.unregister();
}
};
const sendNotification = async () => {
const response = await fetch('/push-notifications/api/send-notification', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({}),
});
const data = await response.json();
console.log(data);
};
export default function PushNotifications() {
const [permissionStatus, setPermissionStatus] = useState<
NotificationPermission | undefined
>();
const requestPermission = async () => {
const permission = await Notification.requestPermission();
setPermissionStatus(permission);
};
useEffect(() => {
const main = async () => {
checkSupport();
requestPermission();
await registerSW();
};
main().catch((err) => {
console.error(err);
});
}, []);
return (
<main className="px-8">
<section className="flex flex-col gap-4 mb-4">
<h1 className="text-lg">Push Notifications</h1>
<p>Basic push notification implementation</p>
</section>
<div className="py-2">
<span className="font-bold">Notification permission:</span>{' '}
{permissionStatus}
</div>
<section className="py-2 flex gap-2">
{permissionStatus && permissionStatus !== 'granted' && (
<Button onClick={requestPermission}>Request permission</Button>
)}
<Button onClick={() => sendNotification()}>Send Notification</Button>
<Button onClick={() => unregisterSW()}>Unregister SW</Button>
</section>
</main>
);
}