Gopinath Kaliappan
Gopinath Kaliappan

Reputation: 7359

How to send push notification to Specific user in Web-push?

I have an existing web site , i just need to push notification to the site, for that i am using Nodejs web-push package , I can able to receive notifications but i need to change it to User Specific,

For Example i want to send the notifications for the users based on the country

This is my code

client.js

const publicVapidKey = 'xxxxxx';

if ('serviceWorker' in navigator) {
  console.log('Registering service worker');

  run().catch(error => console.error(error));
}
function urlBase64ToUint8Array(base64String) {
  const padding = '='.repeat((4 - base64String.length % 4) % 4);
  const base64 = (base64String + padding)
    .replace(/-/g, '+')
    .replace(/_/g, '/');

  const rawData = window.atob(base64);
  const outputArray = new Uint8Array(rawData.length);

  for (let i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i);
  }
  return outputArray;
}

async function run() {
  console.log('Registering service worker');
  const registration = await navigator.serviceWorker.
    register('worker.js');
  console.log('Registered service worker');

  console.log('Registering push');
  const subscription = await registration.pushManager.
    subscribe({
      userVisibleOnly: true,
      // The `urlBase64ToUint8Array()` function is the same as in
      // https://www.npmjs.com/package/web-push#using-vapid-key-for-applicationserverkey
      applicationServerKey: urlBase64ToUint8Array(publicVapidKey)
    });
    // subscription.user = $('.header-user-name').find('span').text();
  console.log('Registered push');

  console.log('Sending push');
  await fetch('http://localhost:3000/subscribe?user='+$('.header-user-name').find('span').text(), {
    method: 'POST',
    body: JSON.stringify(subscription),
    headers: {
      'content-type': 'application/json'
    }
  });
  console.log('Sent push');
}

Worker.js

console.log('Loaded service worker!');

self.addEventListener('push', ev => {
  const data = ev.data.json();
  console.log('Got push', data);

  ev.waitUntil(self.registration.showNotification(data.title, {
    body: 'Hello, World!',
    registration_ids: [$('.header-user-name').find('span').text()]
    icon: 'http://mongoosejs.com/docs/images/mongoose5_62x30_transparent.png'
  }));

});

Server Code (localhost:3000/push)

app.get('/push',function(req,res) {

  const payload = JSON.stringify({ title: 'Hello '+ user.name +' ' + req.query.title,  });

  console.log(req.query);
  console.log("yahooooooooooooooooooooooooooooooooo");

  webpush.sendNotification(newSubscription, payload).catch(error => {
    console.error(error.stack);
  });
  res.send({result : 'Success'});
});

Upvotes: 3

Views: 9436

Answers (2)

Gopinath Kaliappan
Gopinath Kaliappan

Reputation: 7359

After long gap, I got a solution for this problem.

Steps to be followed:

  1. Create an ExpressJs api to store the user subscription in to a database.
  2. Get the user based on countries from database (you can use your own backend language I have chosen Nodejs).
  3. Create an api which can send push notifications using given parameter like (Country, Users, Etc).

Happy Coding.

Upvotes: 3

You can use the users' IPs to look up their countries by using a service like ip-api.com. After you get the country info, you can include it in your request body along with the push subscription object and send to your backend. So, you will have the opportunity to segment your subscribers and send them push notifications with different content.

Upvotes: 1

Related Questions