-
Notifications
You must be signed in to change notification settings - Fork 72
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #351 from near/DEC-1440
Notifications - handle Turn On action
- Loading branch information
Showing
2 changed files
with
41 additions
and
0 deletions.
There are no files selected for viewing
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
}); | ||
}; |