Technology Encyclopedia Home >How to implement push notification service in web application?

How to implement push notification service in web application?

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:

1. Set Up the Push Notification Service

  • Choose a Push Notification Service Provider: You can use a service like Firebase Cloud Messaging (FCM) or OneSignal. These services provide APIs to send push notifications to web, mobile, and desktop applications.
  • Configure the Service: Follow the provider's documentation to set up your project and obtain the necessary credentials (e.g., API keys).

2. Register Devices for Push Notifications

  • Request Permission: Use the browser's Notification API to request permission from the user to send push notifications.
    if ('Notification' in window) {
      Notification.requestPermission().then(permission => {
        if (permission === 'granted') {
          console.log('Push notification permission granted.');
        } else {
          console.log('Push notification permission denied.');
        }
      });
    }
    
  • Subscribe to Push Service: Use the Push API to subscribe the user's browser to push notifications. This involves generating a subscription object that contains the user's endpoint and public key.
    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
        });
      });
    }
    
  • Send Subscription to Server: The subscription object needs to be sent to your server for storage. This allows your server to send push notifications to the user's device.

3. Send Push Notifications from the Server

  • Store Subscriptions: Store the subscription objects in your database.
  • Send Notifications: Use the push notification service provider's API to send notifications to the stored subscriptions.
    • Example with Firebase Cloud Messaging (FCM):
      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);
        });
      
    • Example with OneSignal:
      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);
      };
      

4. Handle Push Notifications in the Service Worker

  • Listen for Push Events: In your service worker, listen for the 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));
    });
    

5. Optional: Use Tencent Cloud for Push Notifications

  • Tencent Cloud Push Service: If you are looking for a robust and scalable solution, consider using Tencent Cloud's Push Service. It provides comprehensive APIs and tools for managing push notifications across multiple platforms, including web, mobile, and IoT devices.
  • Integration: Integrate Tencent Cloud Push Service into your application by following their documentation. You can use their SDKs and APIs to manage subscriptions, send notifications, and analyze notification performance.

By following these steps, you can implement a push notification service in your web application, ensuring that users receive timely and relevant updates.