-
Notifications
You must be signed in to change notification settings - Fork 0
/
2index.html
84 lines (78 loc) · 3.17 KB
/
2index.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<!DOCTYPE html>
<html>
<head>
<title>Firebase Notification Demo</title>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-messaging.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_PROJECT_ID.appspot.com",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID",
measurementId: "YOUR_MEASUREMENT_ID"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
// Function to request notification permission and get the token
function requestPermissionAndGetToken() {
messaging.requestPermission()
.then(() => {
console.log('Notification permission granted.');
return messaging.getToken();
})
.then((token) => {
console.log('Device token:', token);
// Send the token to your Django backend
fetch('http://localhost:8000/send-token/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ token: token }),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
})
.catch((err) => {
console.log('Unable to get permission to notify.', err);
});
}
// Handle incoming messages
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
// Customize notification here
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: payload.notification.icon
};
new Notification(notificationTitle, notificationOptions);
});
// Register service worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/firebase-messaging-sw.js')
.then((registration) => {
console.log('Service Worker registered with scope:', registration.scope);
messaging.useServiceWorker(registration);
}).catch((err) => {
console.log('Service Worker registration failed:', err);
});
}
</script>
</head>
<body>
<h1>Firebase Notification Demo</h1>
<button id="subscribe" onclick="requestPermissionAndGetToken()">Subscribe to Notifications</button>
</body>
</html>