-
Notifications
You must be signed in to change notification settings - Fork 231
Expand file tree
/
Copy pathfcm.js
More file actions
55 lines (45 loc) · 1.56 KB
/
fcm.js
File metadata and controls
55 lines (45 loc) · 1.56 KB
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
import { useEffect } from 'react';
import firebase from 'firebase/app';
import 'firebase/messaging';
// Initialize Firebase
const firebaseConfig = {
// Your Firebase config here
};
firebase.initializeApp(firebaseConfig);
const YourComponent = () => {
useEffect(() => {
const requestNotificationPermission = async () => {
try {
const messaging = firebase.messaging();
await messaging.requestPermission();
console.log('Notification permission granted.');
const token = await messaging.getToken();
console.log('Registration token:', token);
// Send the registration token to your server for further processing/storage if needed
} catch (error) {
console.log('Error retrieving registration token:', error);
}
};
const sendNotification = async () => {
try {
const messaging = firebase.messaging();
const registrationToken = 'DEVICE_REGISTRATION_TOKEN'; // Replace with the actual device registration token
await messaging.send({
token: registrationToken,
notification: {
title: 'Notification Title',
body: 'Notification Description',
image: 'URL_TO_IMAGE', // Replace with the URL of the image you want to send
},
});
console.log('Notification sent successfully.');
} catch (error) {
console.log('Unable to send notification.', error);
}
};
requestNotificationPermission().then(() => {
sendNotification();
});
}, []);
// Rest of your component code
};