-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmessaging.js
83 lines (74 loc) · 2.68 KB
/
messaging.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
/*===================================================================//
VERSION 8 (current)
//===================================================================*/
import { messaging } from "./init-firebase";
// Get a registration token
const getRegistrationToken = async (publicKey) => {
await messaging
.getToken({ vapidKey: publicKey })
.then((currentToken) => {
if (currentToken) {
// Send the token to your server and update the UI if necessary
console.log(currentToken);
} else {
console.log("No registration token available. Request permission to generate one.");
}
})
.catch((err) => {
console.log("An error occurred while retrieving token. ", err);
// .
});
};
// Handle foreground messages
messaging.onMessage((payload) => {
console.log("Message received. ", payload);
// ...
});
// Handle background message from a service worker (firebase-messaging.js)
messaging.onBackgroundMessage((payload) => {
console.log("[firebase-messaging-sw.js] Received background message ", payload);
// Customize notification here
const notificationTitle = "Some Title";
const notificationOptions = {
body: "Some content",
icon: "/some-icon-file.png",
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
/*===================================================================//
VERSION 9 (beta)
//===================================================================*/
import { messaging } from "./init-firebase";
import { getToken, onMessage, onBackgroundMessage } from "firebase/messaging";
// Get a registration token
const getRegistrationToken = async (publicKey) => {
await getToken(messaging, { vapidKey: publicKey })
.then((currentToken) => {
if (currentToken) {
// Send the token to your server and update the UI if necessary
console.log(currentToken);
} else {
console.log("No registration token available. Request permission to generate one.");
}
})
.catch((err) => {
console.log("An error occurred while retrieving token. ", err);
// .
});
};
// Handle foreground messages
onMessage(messaging, (payload) => {
console.log("Message received. ", payload);
// ...
});
// Handle background message from a service worker (firebase-messaging.js)
onBackgroundMessage(messaging, (payload) => {
console.log("[firebase-messaging-sw.js] Received background message ", payload);
// Customize notification here
const notificationTitle = "Some Title";
const notificationOptions = {
body: "Some content",
icon: "/some-icon-file.png",
};
self.registration.showNotification(notificationTitle, notificationOptions);
});