Implementing a push notification service in a web application involves several steps, including setting up the necessary infrastructure, registering devices, and sending notifications. Here's a detailed explanation with an example:
if ('Notification' in window) {
Notification.requestPermission().then(permission => {
if (permission === 'granted') {
console.log('Push notification permission granted.');
} else {
console.log('Push notification permission denied.');
}
});
}
if ('serviceWorker' in navigator && 'PushManager' in window) {
navigator.serviceWorker.register('/service-worker.js').then(swReg => {
console.log('Service Worker is registered', swReg);
swReg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array('YOUR_PUBLIC_VAPID_KEY')
}).then(subscription => {
console.log('User is subscribed:', subscription);
// Send the subscription object to your server
});
});
}
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.applicationDefault()
});
const message = {
notification: {
title: 'Hello',
body: 'This is a push notification!'
},
webpush: {
fcmOptions: {
link: 'https://example.com'
}
},
tokens: ['USER_SUBSCRIPTION_TOKEN']
};
admin.messaging().sendMulticast(message)
.then((response) => {
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
const axios = require('axios');
const sendNotification = async (userId, message) => {
const response = await axios.post('https://onesignal.com/api/v1/notifications', {
app_id: 'YOUR_ONESIGNAL_APP_ID',
include_player_ids: [userId],
contents: { en: message }
}, {
headers: {
'Authorization': `Basic YOUR_ONESIGNAL_REST_API_KEY`,
'Content-Type': 'application/json'
}
});
console.log('Notification sent:', response.data);
};
push event and display the notification.self.addEventListener('push', event => {
const title = 'New Notification';
const options = {
body: event.data.text(),
icon: '/icon.png'
};
event.waitUntil(self.registration.showNotification(title, options));
});
By following these steps, you can implement a push notification service in your web application, ensuring that users receive timely and relevant updates.