-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfirebase_client.js
149 lines (134 loc) · 5.79 KB
/
firebase_client.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
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 "https://www.gstatic.com/firebasejs/9.11.0/firebase-app.js";
import {getMessaging, getToken, onMessage} from "https://www.gstatic.com/firebasejs/9.11.0/firebase-messaging.js";
// Web app's Firebase configuration
// Should be copied during project initialization
const firebaseConfig = {
apiKey: "AIzaSyD4kj2g3e_SOQTmzBUtDn2_vx6UvcdWiG8",
authDomain: "kulikov-dev.firebaseapp.com",
projectId: "kulikov-dev",
storageBucket: "kulikov-dev.appspot.com",
messagingSenderId: "441130914859",
appId: "1:441130914859:web:2cb9c5736e4a595af0066e"
};
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);
// URL to your site webhook for saving an user token.
const webhook_url = '';
const tokenSentLocalTitle = 'tokenSentToServer';
// 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);
// In case if need to show notification even for current focused tab of your page
payload.data.data = JSON.parse(JSON.stringify(payload.data));
navigator.serviceWorker.getRegistration('/firebase-cloud-messaging-push-scope').then(registration => {
registration.showNotification(
payload.data.title,
payload.data
)
});
// TODO Update UI if necessary to show the received message.
});
// Check if browser supports push-notifications
if (
!('Notification' in window &&
'serviceWorker' in navigator &&
'localStorage' in window &&
'fetch' in window &&
'postMessage' in window)
) {
if (!('Notification' in window)) {
console.error('Notification not supported');
} else if (!('serviceWorker' in navigator)) {
console.error('ServiceWorker not supported');
} else if (!('localStorage' in window)) {
console.error('LocalStorage not supported');
} else if (!('fetch' in window)) {
console.error('fetch not supported');
} else if (!('postMessage' in window)) {
console.error('postMessage not supported');
}
console.warn('This browser does not support push-notifications.');
console.log('Is HTTPS', window.location.protocol === 'https:');
console.log('Support Notification', 'Notification' in window);
console.log('Support ServiceWorker', 'serviceWorker' in navigator);
console.log('Support LocalStorage', 'localStorage' in window);
console.log('Support fetch', 'fetch' in window);
console.log('Support postMessage', 'postMessage' in window);
} else {
if (Notification.permission === 'granted') {
getUserToken();
} else {
requestPermission();
}
}
// Request user permission for push-notifications
function requestPermission() {
console.log('Requesting permission...');
Notification.requestPermission().then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.');
getUserToken();
} else {
console.log('Unable to get permission to notify.');
}
});
}
// Get user registration token
function getUserToken() {
// Register a service worker to use script with github pages. As firebase required to store serviceWorker only in the root.
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("/firebase-push/firebase-messaging-sw.js")
.then(function (registration) {
console.log("Registration successful, scope is:", registration.scope);
// Get registration token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
getToken(messaging, {
vapidKey: 'BKpTvOreKY6M4vca8Qy1GfLda9seP0BaWFnkFaGvstDRknLfwDuTRHNPS8te28IP1Imm9LvZm0Q3GJwz7NuCDQg',
serviceWorkerRegistration: registration
}).then((currentToken) => {
if (currentToken) {
sendTokenToServer(currentToken);
} else {
// Show permission request.
console.log('No registration token available. Request permission to generate one.');
setTokenSentToServer(false);
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
setTokenSentToServer(false);
});
})
.catch(function (err) {
console.log("Service worker registration failed, error:", err);
});
}
}
// 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) {
if (!isTokenSentToServer()) {
console.log('Sending token to server...');
window.localStorage.setItem('token', currentToken);
setTokenSentToServer(true);
if (webhook_url) {
// TODO: Send the current token to your server.
$.post(webhook_url, {token: currentToken}, function () {
console.log('Token sent to the server...');
});
}
} else {
console.log('Token already sent to server so won\'t send it again unless it changes');
}
}
// Update local information about token been sent to the server
function setTokenSentToServer(sent) {
window.localStorage.setItem(tokenSentLocalTitle, sent ? '1' : '0');
}
// Check local information if token was sent to server
function isTokenSentToServer() {
return window.localStorage.getItem(tokenSentLocalTitle) === '1';
}