Pushpad
Articles › Sending Notifications, Web Push Notifications

How to send notifications with JavaScript (in 10 lines of code)

  • # web-notifications

It's very simple to display a native notification using JavaScript.

<script>
  function showNotification() {
    Notification.requestPermission().then(permission => {
      if (permission == 'granted') {
        new Notification("Example Notification", { body: "The content of the notification." })
      }
    })
  }
</script>

<button onclick="showNotification()">Send Notification</button>

When you click the button, the code will first request the permission to display notifications and then it will display a notification.

The only issue with the above code is that the web app / website needs to be open in order to display the notification.

If you want to send the notifications even when the website is closed you will need to use a more complex stack of technologies (Push API, WebPush, Service Workers, etc.) or a service like Pushpad.