Skip to content

Commit

Permalink
Merge pull request #351 from near/DEC-1440
Browse files Browse the repository at this point in the history
Notifications - handle Turn On action
  • Loading branch information
marcinbodnar authored Sep 5, 2023
2 parents 51ffdc4 + 85ea4a5 commit b0b537b
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
Empty file added public/service-worker.js
Empty file.
41 changes: 41 additions & 0 deletions src/utils/notifications.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const applicationServerKey = '';
const HOST = '/subscriptions/create';

export const isNotificationSupported = () => typeof window !== 'undefined' && 'Notification' in window;

export const isPushManagerSupported = () => typeof window !== 'undefined' && 'PushManager' in window;

export const isPermisionGranted = () => Notification.permission === 'granted';

const handleRequestPermission = () => Notification.requestPermission();

const registerServiceWorker = () => navigator.serviceWorker.register('/service-worker.js');

const handlePushManagerSubscribe = async () => {
const serviceWorker = await navigator.serviceWorker.ready;

return await serviceWorker.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey,
});
};

const sendToPushServer = (subscriptionData: object) =>
fetch(HOST, {
method: 'POST',
body: JSON.stringify(subscriptionData),
});

export const handleTurnOn = async (accountId: string) => {
if (!isNotificationSupported() && !isPushManagerSupported() && isPermisionGranted()) {
return;
}

await handleRequestPermission();
await registerServiceWorker();
const subscription = await handlePushManagerSubscribe();
await sendToPushServer({
subscription,
accountId,
});
};

0 comments on commit b0b537b

Please sign in to comment.