forked from kenng/firebase-push-notification-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
68 lines (62 loc) · 2.54 KB
/
index.html
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
<html>
<title>Firebase Messaging Demo</title>
<style>
div {
margin-bottom: 15px;
}
</style>
<body>
<div id="token"></div>
<div id="msg"></div>
<div id="notis"></div>
<div id="err"></div>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.4.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.16.1/firebase-messaging.js"></script>
<script>
MsgElem = document.getElementById('msg');
TokenElem = document.getElementById('token');
NotisElem = document.getElementById('notis');
ErrElem = document.getElementById('err');
// TODO: Replace firebaseConfig you get from Firebase Console
var firebaseConfig = {
// apiKey: ...
// projectId: ...
// messagingSenderId: ...
// appId: ...
// ...other configs...
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
messaging
.requestPermission()
.then(function () {
MsgElem.innerHTML = 'Notification permission granted.';
console.log('Notification permission granted.');
// get the token in the form of promise
return messaging.getToken();
})
.then(function (token) {
TokenElem.innerHTML = 'Device token is : <br>' + token;
})
.catch(function (err) {
ErrElem.innerHTML = ErrElem.innerHTML + '; ' + err;
console.log('Unable to get permission to notify.', err);
});
let enableForegroundNotification = true;
messaging.onMessage(function (payload) {
console.log('Message received. ', payload);
NotisElem.innerHTML =
NotisElem.innerHTML + JSON.stringify(payload);
if (enableForegroundNotification) {
let notification = payload.notification;
navigator.serviceWorker
.getRegistrations()
.then((registration) => {
registration[0].showNotification(notification.title);
});
}
});
</script>
</body>
</html>