Introduction:
Broadcasting notifications to all users of your web app involves sending notifications to a topic in Firebase Cloud Messaging (FCM). All users who have subscribed to that topic will receive the notification. Here’s how you can achieve this:
Front-End Setup:
- Integrate the Firebase JavaScript SDK into your web app.
- Request permission from users to receive notifications.
- Subscribe users to a specific topic using their FCM tokens.
<!– Include the Firebase JavaScript SDK –>
<script src=”https://www.gstatic.com/firebasejs/9.6.1/firebase-app.js”></script>
<script src=”https://www.gstatic.com/firebasejs/9.6.1/firebase-messaging.js”></script>
<script>
// Initialize Firebase
const firebaseConfig = {
apiKey: “YOUR_API_KEY”,
authDomain: “your-app.firebaseapp.com”,
projectId: “your-app”,
storageBucket: “your-app.appspot.com”,
messagingSenderId: “YOUR_MESSAGING_SENDER_ID”,
appId: “YOUR_APP_ID”
};
firebase.initializeApp(firebaseConfig);
// Request permission for notifications
const messaging = firebase.messaging();
messaging.requestPermission()
.then(() => {
return messaging.getToken();
})
.then((token) => {
console.log(“Token:”, token);
// Send the token to your server for later use
subscribeToBroadcastTopic(token);
})
.catch((error) => {
console.error(“Permission denied or error getting token:”, error);
});
// Subscribe user to the broadcast topic
function subscribeToBroadcastTopic(token) {
fetch(‘https://iid.googleapis.com/iid/v1/’ + token + ‘/rel/topics/broadcast’, {
method: ‘POST’,
headers: new Headers({
‘Authorization’: ‘key=YOUR_SERVER_KEY’
})
})
.then(response => {
if (response.status < 200 || response.status >= 400) {
console.error(‘Error subscribing to topic:’, response.statusText);
} else {
console.log(‘Subscribed to broadcast topic’);
}
})
.catch(error => {
console.error(‘Error subscribing to topic:’, error);
});
}
</script>
Back-End Setup (PHP):
- Implement a PHP script on your server to send notifications to the broadcast topic.
<?php
$serverKey = ‘YOUR_SERVER_KEY’; // Replace with your Firebase Server Key
$data = [
‘to’ => ‘/topics/broadcast’,
‘notification’ => [
‘title’ => ‘Notification Title’,
‘body’ => ‘Notification Body’,
],
];
$options = [
‘http’ => [
‘header’ => “Content-Type: application/json\r\nAuthorization: key=$serverKey”,
‘method’ => ‘POST’,
‘content’ => json_encode($data),
],
];
$context = stream_context_create($options);
$result = file_get_contents(‘https://fcm.googleapis.com/fcm/send’, false, $context);
if ($result === FALSE) {
echo “Error sending broadcast notifications.”;
} else {
echo “Broadcast notifications sent successfully.”;
}
?>
In this setup:
- The front-end subscribes each user’s FCM token to the “broadcast” topic.
- The back-end sends a notification to the “/topics/broadcast” destination, which will target all users subscribed to that topic.
Please make sure to replace 'YOUR_SERVER_KEY'
with your actual Firebase Server Key and handle errors and security aspects appropriately in your production environment.