Tag Archives: javascript send push notification permission

How to send push notification to web browser

What is push notification

Web push notifications are clickable rich content messages sent to your device by a website or a web app. Web Push notifications can delivered to your device, mobile or desktop, even when the user is not on your website.

What is push notification

What is push notification

These notifications can only be sent to users who have opted-in to receive these notifications. Web push notifications or browser notifications are supported by Chrome, Firefox, Edge and Safari.

Why Push Notifications

Web Push Notifications allow users to opt-in for timely updates from web apps that aim to re-engage their user base with content that might be interesting, important and well-timed for the users.

Push API

The Push API gives web applications the ability to receive messages pushed to them from a server, whether or not the web app is in the foreground, or even currently loaded, on a user agent. This lets developers deliver asynchronous notifications and updates to users that opt in, resulting in better engagement with timely new content.

Example to get user permission and send push notification


<script>// request permission on page load
document.addEventListener('DOMContentLoaded', function () {
  if (!Notification) {
    alert('Desktop notifications not available in your browser. Try Chromium.'); 
    return;
  }

  if (Notification.permission !== "granted")
    Notification.requestPermission();
});

function notifyMe() {
  if (Notification.permission !== "granted")
    Notification.requestPermission();
  else {
    var notification = new Notification('Welcome to ptutorial', {
      icon: 'http://www.ptutorial.com/icon/umar.ico',
      body: "New post created",
    });

    notification.onclick = function () {
      window.open("http://blogs.ptutorial.com");      
    };

  }

}</script>

Conclusion

You can use the above script to send push notification to web browser. You can also use this script with firefase or socket.io to send real time notification.