Skip to content

Instantly share code, notes, and snippets.

@oahehc
Created September 30, 2020 03:44
Show Gist options
  • Save oahehc/5ed1eab58598974d9d560365e3466980 to your computer and use it in GitHub Desktop.
Save oahehc/5ed1eab58598974d9d560365e3466980 to your computer and use it in GitHub Desktop.
// Get permission & subscription
if (Notification && Notification.permission === "default") {
Notification.requestPermission().then((result) => {
if (result === "denied") {
return;
}
if (result === "granted") {
if (navigator && navigator.serviceWorker) {
navigator.serviceWorker.ready.then((reg) => {
reg.pushManager
.getSubscription()
.then((subscription: any) => {
if (!subscription) {
// we need to encrypt the data for web push notification,
// I use web-push to generate the public and private key.
// You can check their documentation for more detail.
// https://github.com/web-push-libs/web-push
const vapidPublicKey = "xxxxx";
const applicationServerKey =
urlBase64ToUint8Array(vapidPublicKey);
return reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey,
});
}
return subscription;
})
.then((sub) => {
// Get the subscription information here, we need to
// create an API and save them into our database
/*
{
endpoint:
"https://fcm.googleapis.com/fcm/send/xxx",
keys: {
auth: "xxx",
p256dh: "xxx",
},
};
*/
});
});
}
}
});
}
// send notification
const webpush = require('web-push');
webpush.setVapidDetails("mailto:[email protected]", "my_private_key");
const pushConfig = {
endpoint: sub.endpoint,
keys: {
auth: sub.keys.auth,
p256dh: sub.keys.p256dh,
},
};
webpush
.sendNotification(
pushConfig,
JSON.stringify({ title: "Test Title", content: "Test Content" })
)
.catch((err) => {
console.log(err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment