Pushpad
Articles › Targeting Users, Web Push Notifications

Is it possible to send a web push message from a browser to another?

  • # push-api
  • # targeting

I've seen this question several times, so I would like to give a definitive answer.

It's not possible to use the W3C Push API to send the notifications directly between two browsers. The reason is simple: security.

When you send a notification from a website, you need to sign it with some secret keys (VAPID) and then deliver it to a secret URL (endpoint) which represents the recipient. The VAPID private key, the endpoint and other secret data must remain on your server.

Giving the private data to a browser, would mean exposing all your users to spam: a malicious user could read those keys, sign the notifications as if it was your website, and then send any kind of notifications to your users.

This means that you cannot send a notification directly from a browser to another.

However you can achieve something similar using some server-side code.

Let's see an example using Pushpad (but a similar strategy should be applicable to any web push service or application).

First you need to assign a user ID to a browser that subscribes to notifications (so that you can target it later with notifications):

pushpad('subscribe', null, { uid: 'user1', uidSignature: 'the signature' });

Then from another browser you can send a custom message to your server:

fetch('https://example.com/send', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ message: 'Hello', recipient: 'user1' }),
})

Finally the server can deliver the message to the recipient:

# all secrets can remain on the server

$notification = new Pushpad\Notification(array(
  'title' => $current_user . ' sent you a message:',
  'body' => $_POST["message"]
));
$notification->deliver_to($_POST["recipient"]);

Probably you also want to save the message on your server (e.g. chat) and you don't want to allow any user to send a message to any other user, but this is the basic code that you can improve.