This repository has been archived by the owner on Feb 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmsg.js
63 lines (53 loc) · 1.99 KB
/
msg.js
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
// init messaging
const messaging = firebase.messaging()
// init database to store fcm token
const database = firebase.firestore().collection("fcmTokens")
// to store fcm token of the device
var token = "";
// content placeholder
const content = document.querySelector(".sub");
// redirect if any external link mentioned
var redirect = window.location.href.split("=")[1];
if (redirect!="" && redirect!=undefined) {
window.location.href=redirect;
}
// gets fcm token if subscribed to fcm
const getFCMToken = async () => {
await messaging.getToken({vapid:'<PUBLIC VAPID KEY>'}).then((a)=>{token = a})
// Replace <PUBLIC VAPID KEY> with your project's valip key pair.
// You can find that at https://console.firebase.google.com/u/0/project/_/settings/cloudmessaging under Web Configurations > Web Push Certificates > Key Pair. If not available, generate one.
return token;
}
// displays fcm token in the placeholder
const showFCMToken = async () => {
await getFCMToken();
console.log(token);
content.innerHTML = "<h4>FCM Token</h4><p>"+token+"</p>";
}
// requests permission for notification
const requestPermission = () => {
messaging.requestPermission().then(async () => {
token = await getFCMToken();
database.doc().set({
token: token
}).then(() => {
showFCMToken();
}).catch((err) => {
Notification.permission=="default";
alert(err.message);
})
}).catch((err) => {
alert("You've blocked the notifications. Please check your browser settings");
})
}
// checks whether the user is already subscribed to notifications
if (Notification.permission=="granted") {
showFCMToken();
}
// defines what to do when a new notification arrives if the website is open
messaging.onMessage((msg) => {
content.innerHTML = "<h4>" + msg.notification.title + "</h4><p>" + msg.notification.body + "</p>";
});
/*******************************************************/
/******************************************************/
/*****************************************************/