How to send push notification to web browser?

JavascriptGoogle Cloud-MessagingWeb NotificationsWeb PushPush Api

Javascript Problem Overview


I have been reading for past few hours about Push Notification API and Web Notification API. I also discovered that Google & Apple gives push notification service for free via GCM and APNS respectively.

I am trying to understand if we can implement push notification to browsers using Desktop Notification, which I believe is what Web Notification API does. I saw a google documentation on how this can be done for Chrome here & here.

Now what am still not able to understand is:

  1. Can we use GCM/APNS to send push notification to all Web Browsers including Firefox & Safari?
  2. If not via GCM can we have our own back-end to do the same?

I believe all these answered in one answer can help a lot of people who are having similar confusions.

Javascript Solutions


Solution 1 - Javascript

So here I am answering my own question. I have got answers to all my queries from people who have build push notification services in the past.

> > Update (May 2018): > Here is a comprehensive and a very well written doc on web push notification from Google.

Answer to the original questions asked 3 years ago: >
> > 1. Can we use GCM/APNS to send push notification to all Web Browsers > including Firefox & Safari?

Answer: Google has deprecated GCM as of April 2018. You can now use Firebase Cloud Messaging (FCM). This supports all platforms including web browsers.

> 2. If not via GCM can we have our own back-end to do the same?

Answer: Yes, push notification can be sent from our own back-end. Support for the same has come to all major browsers.

Check this codelab from Google to better understand the implementation.

Some Tutorials:

  • Implementing push notification in Django Here.
  • Using flask to send push notification Here & Here.
  • Sending push notifcaiton from Nodejs Here
  • Sending push notification using php Here & Here
  • Sending push notification from Wordpress. Here & Here
  • Sending push notification from Drupal. Here

Implementing own backend in various programming languages.:

Further Readings:

Are there any free services to do the same? There are some companies that provide a similar solution in free, freemium and paid models. Am listing few below:

  1. https://onesignal.com/ (Free | Support all platforms)
  2. https://firebase.google.com/products/cloud-messaging/ (Free)
  3. https://clevertap.com/ (Has free plan)
  4. https://goroost.com/

Note: When choosing a free service remember to read the TOS. Free services often work by collecting user data for various purposes including analytics.

Apart from that, you need to have HTTPS to send push notifications. However, you can get https freely via letsencrypt.org

Solution 2 - Javascript

Javier covered Notifications and current limitations.

My suggestion: window.postMessage while we wait for the handicapped browser to catch up, else Worker.postMessage() to still be operating with Web Workers.

These can be the fallback option with dialog box message display handler, for when a Notification feature test fails or permission is denied.

Notification has-feature and denied-permission check:

if (!("Notification" in window) || (Notification.permission === "denied") ) {
	// use (window||Worker).postMessage() fallback ...
}

Solution 3 - Javascript

You can push data from the server to the browser via Server Side Events. This is essentially a unidirectional stream that a client can "subscribe" to from a browser. From here, you could just create new Notification objects as SSEs stream into the browser:

var source = new EventSource('/events');

source.on('message', message => {
  var notification = new Notification(message.title, {
    body: message.body
  });
}); 

A bit old, but this article by Eric Bidelman explains the basics of SSE and provides some server code examples as well.

Solution 4 - Javascript

this is simple way to do push notification for all browser https://pushjs.org

Push.create("Hello world!", {
body: "How's it hangin'?",
icon: '/icon.png',
timeout: 4000,
onClick: function () {
    window.focus();
    this.close();
 }
});

Solution 5 - Javascript

GCM/APNS are only for Chrome and Safari respectively.

I think you may be looking for Notification:

https://developer.mozilla.org/en-US/docs/Web/API/notification

It works in Chrome, Firefox, Opera and Safari.

Solution 6 - Javascript

I assume you are talking about real push notifications that can be delivered even when the user is not surfing your website (otherwise check out WebSockets or legacy methods like long polling).

> Can we use GCM/APNS to send push notification to all Web Browsers including Firefox & Safari?

GCM is only for Chrome and APNs is only for Safari. Each browser manufacturer offers its own service.

> If not via GCM can we have our own back-end to do the same?

The Push API requires two backends! One is offered by the browser manufacturer and is responsible for delivering the notification to the device. The other one should be yours (or you can use a third party service like Pushpad) and is responsible for triggering the notification and contacting the browser manufacturer's service (i.e. GCM, APNs, Mozilla push servers).

Disclosure: I am the Pushpad founder

Solution 7 - Javascript

May I redefine you question as below > Can we have our own back-end to send push notification to Chrome, Firefox, Opera & Safari?

Yes. By today (2017/05), you can use same client and server side implementation to handle Chrome, Firefox and Opera (no Safari). Because they have implemented web push notifications in a same way. That is Push API protocol by W3C. But Safari have their own old architecture. So we have to maintain Safari separately.

Refer browser-push repo for guide lines to implement web push notification for your web-app with your own back-end. It explains with examples how you can add web push notification support for your web application without any third party services.

Solution 8 - Javascript

As of now GCM only works for chrome and android. similarly firefox and other browsers has their own api.

Now coming to the question how to implement push notification so that it will work for all common browsers with own back end.

  1. You need client side script code i.e service worker,refer( Google push notification). Though this remains same for other browsers.

2.after getting endpoint using Ajax save it along with browser name.

3.You need to create back end which has fields for title,message, icon,click URL as per your requirements. now after click on send notification, call a function say send_push(). In this write code for different browsers for example

3.1. for chrome

 $headers = array(
	      'Authorization: key='.$api_key(your gcm key),
	      'Content-Type: application/json',
	 );
   $msg = array('to'=>'register id saved to your server');
   $url = 'https://android.googleapis.com/gcm/send';
   $ch = curl_init();
	
	  // Set the url, number of POST vars, POST data
	  curl_setopt($ch, CURLOPT_URL, $url);
	  curl_setopt($ch, CURLOPT_POST, true);
	  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($msg));
			
	  $result = curl_exec($ch);

3.2. for mozilla

$headers = array(		     
		      'Content-Type: application/json',
              'TTL':6000
			);
     
       $url = 'https://updates.push.services.mozilla.com/wpush/v1/REGISTER_ID_TO SEND NOTIFICATION_ON';
      
      $ch = curl_init();
	
	  // Set the url, number of POST vars, POST data
	  curl_setopt($ch, CURLOPT_URL, $url);
	  curl_setopt($ch, CURLOPT_POST, true);
	  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	
			
	  $result = curl_exec($ch);
  

for other browsers please google...

Solution 9 - Javascript

I suggest using pubnub. I tried using ServiceWorkers and PushNotification from the browser however, however when I tried it webviews did not support this.

https://www.pubnub.com/docs/web-javascript/pubnub-javascript-sdk

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionesafwanView Question on Stackoverflow
Solution 1 - JavascriptesafwanView Answer on Stackoverflow
Solution 2 - Javascriptgreg.arnottView Answer on Stackoverflow
Solution 3 - JavascriptdjfdevView Answer on Stackoverflow
Solution 4 - Javascriptabderrahime sanadiView Answer on Stackoverflow
Solution 5 - JavascriptJavier CondeView Answer on Stackoverflow
Solution 6 - JavascriptcollimarcoView Answer on Stackoverflow
Solution 7 - JavascriptTRiNEView Answer on Stackoverflow
Solution 8 - JavascriptArjun singhView Answer on Stackoverflow
Solution 9 - JavascriptColacXView Answer on Stackoverflow