forked from firebase/quickstart-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
149 lines (130 loc) · 4.94 KB
/
main.ts
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import { initializeApp } from 'firebase/app';
import { MessagePayload, deleteToken, getMessaging, getToken, onMessage } from 'firebase/messaging';
import { firebaseConfig, vapidKey } from './config';
initializeApp(firebaseConfig);
const messaging = getMessaging();
// IDs of divs that display registration token UI or request permission UI.
const tokenDivId = 'token_div';
const permissionDivId = 'permission_div';
// Handle incoming messages. Called when:
// - a message is received while the app has focus
// - the user clicks on an app notification created by a service worker
// `messaging.onBackgroundMessage` handler.
onMessage(messaging, (payload) => {
console.log('Message received. ', payload);
// Update the UI to include the received message.
appendMessage(payload);
});
function resetUI() {
clearMessages();
showToken('loading...');
// Get registration token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
getToken(messaging, { vapidKey }).then((currentToken) => {
if (currentToken) {
sendTokenToServer(currentToken);
updateUIForPushEnabled(currentToken);
} else {
// Show permission request.
console.log('No registration token available. Request permission to generate one.');
// Show permission UI.
updateUIForPushPermissionRequired();
setTokenSentToServer(false);
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
showToken('Error retrieving registration token.');
setTokenSentToServer(false);
});
}
function showToken(currentToken: string) {
// Show token in console and UI.
const tokenElement = document.querySelector('#token')!;
tokenElement.textContent = currentToken;
}
// Send the registration token your application server, so that it can:
// - send messages back to this app
// - subscribe/unsubscribe the token from topics
function sendTokenToServer(currentToken: string) {
if (!isTokenSentToServer()) {
console.log('Sending token to server...', currentToken);
// TODO(developer): Send the current token to your server.
setTokenSentToServer(true);
} else {
console.log('Token already sent to server so won\'t send it again unless it changes');
}
}
function isTokenSentToServer() {
return window.localStorage.getItem('sentToServer') === '1';
}
function setTokenSentToServer(sent: boolean) {
window.localStorage.setItem('sentToServer', sent ? '1' : '0');
}
function showHideDiv(divId: string, show: boolean) {
const div = document.querySelector('#' + divId)! as HTMLDivElement;
if (show) {
div.style.display = 'block';
} else {
div.style.display = 'none';
}
}
function requestPermission() {
console.log('Requesting permission...');
Notification.requestPermission().then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.');
// TODO(developer): Retrieve a registration token for use with FCM.
// In many cases once an app has been granted notification permission,
// it should update its UI reflecting this.
resetUI();
} else {
console.log('Unable to get permission to notify.');
}
});
}
function deleteTokenFromFirebase() {
// Delete registration token.
getToken(messaging).then((currentToken) => {
deleteToken(messaging).then(() => {
console.log('Token deleted.', currentToken);
setTokenSentToServer(false);
// Once token is deleted update UI.
resetUI();
}).catch((err) => {
console.log('Unable to delete token. ', err);
});
}).catch((err) => {
console.log('Error retrieving registration token. ', err);
showToken('Error retrieving registration token.');
});
}
// Add a message to the messages element.
function appendMessage(payload: MessagePayload) {
const messagesElement = document.querySelector('#messages')!;
const dataHeaderElement = document.createElement('h5');
const dataElement = document.createElement('pre');
dataElement.style.overflowX = 'hidden;';
dataHeaderElement.textContent = 'Received message:';
dataElement.textContent = JSON.stringify(payload, null, 2);
messagesElement.appendChild(dataHeaderElement);
messagesElement.appendChild(dataElement);
}
// Clear the messages element of all children.
function clearMessages() {
const messagesElement = document.querySelector('#messages')!;
while (messagesElement.hasChildNodes()) {
messagesElement.removeChild(messagesElement.lastChild!);
}
}
function updateUIForPushEnabled(currentToken: string) {
showHideDiv(tokenDivId, true);
showHideDiv(permissionDivId, false);
showToken(currentToken);
}
function updateUIForPushPermissionRequired() {
showHideDiv(tokenDivId, false);
showHideDiv(permissionDivId, true);
}
document.getElementById('request-permission-button')!.addEventListener('click', requestPermission);
document.getElementById('delete-token-button')!.addEventListener('click', deleteTokenFromFirebase);
resetUI();