-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.js
88 lines (79 loc) · 2.75 KB
/
app.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Firebase Configurations
var firebaseConfig = {
apiKey: "AIzaSyDDFphd7ioHLcmCfXt-eta8ljX0ex2yV6s",
projectId: "my-project-1409b",
storageBucket: "com.myproject.myproject",
messagingSenderId: "130527465681",
appId: "1:130527465681:android:7ff6c5732b020575e275f0"
};
// Initializing Firebase App
firebase.initializeApp(firebaseConfig);
// Initializing Cloud Messanging
const messaging = firebase.messaging();
// Registering Service worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./sw.js').then(res => {
console.log("Register Success");
messaging.useServiceWorker(res);
}).catch(e => {
console.log(e);
});
}
// Subscribing to push Notifications
const subscribe = () => {
const token = document.getElementById('token');
// getting PushNotification permission from browser
Notification.requestPermission().then(permission => {
if (permission == "granted") {
// if Permission is allowed then getting firebase messanging token from firebase
messaging.getToken().then(currentToken => {
console.log(currentToken);
// displaying token in index file
token.textContent = currentToken;
});
} else {
token.textContent = "Permission not granted";
}
}).catch(e=>{
token.textContent=e;
});
};
// Sending Push Notifications
const sendPush = () => {
// Getting From Data when button clicked
const token = document.getElementById('usertoken').value;
const notificationTitle = document.getElementById('title').value;
const notificationBody = document.getElementById('body').value;
// Adding data to payload for sending push notifications
let body = {
to: token,
notification: {
title: notificationTitle,
body: notificationBody,
click_action: "/",
}
};
// Setting options for push notification
const options = {
method: "POST",
headers: new Headers({
// Add your server key after key=
Authorization: "key=AAAAHmQLENE:APA91bEp6wXGwd8c1L96dh5wJ3x8HVCXM7_XDgxuoj1vhjUo2KfjDPbfGylXR93T6Cc4d-XdcT0rTjE2cq06toP5oFN7knP8bw3wvwiHYekbw2LcSZ3MD6jwrc72HanR9SY_Y27Uillr",
"Content-Type": "application/json"
}),
body: JSON.stringify(body)
};
// Sending Push notifications to user using fetch api
fetch("https://fcm.googleapis.com/fcm/send", options)
.then(res => res.json())
.then(data => {
if (data.failure == 1) {
alert("Token Expire");
} else {
alert("Send Success");
}
})
.catch(err => {
alert(err);
});
};