November 14, 2024

How to Send Push Notifications With JavaScript

Notifications #Notifications

© Provided by MUO

JavaScript notifications are a way to send messages to your users in real-time. You can use them to notify about your website updates, new chat messages, emails, or any social media activities. You can also use notifications for calendar reminders (such as an approaching meeting on Google Meet or Zoom).

Learn how to create event notifications in JavaScript and send them to your phone or web browser. You’ll achieve this using built-in, client-side JavaScript—no external library required!

Requesting Permission to Send Notifications

To create a notification, you need to call the Notification class to create an object. It gives you access to various properties and methods that you can use to configure your notification. But before creating a notification, you’ll need to first request permission from the user.

The following JavaScript will request permission to send user notifications. The requestPermission call will return a message indicating whether the browser allows notifications or not:

const button = document.querySelector(‘button’)

  button.addEventListener(“click”, ()=> {

  Notification.requestPermission().then(permission => {

    alert(permission)

  })

})

When you click on the button, you may get an alert that says denied. This means that the browser has denied JavaScript from sending event notifications. The permission status is denied for cases where the user has explicitly prevented the sites to send notifications (through browser settings) or the user is surfing in incognito mode.

For such cases, it’s better to respect the user’s decision for denied notifications and you should refrain from further bothering them.

Sending Basic Notifications

You create a push notification by creating a Notification object with the new keyword. For a deep dive into object-oriented programming, you can refer to our guide on how to create classes in JavaScript.

Since you’d send notifications only if permission is granted, you’d need to wrap it inside an if check.

const button = document.querySelector(‘button’)

button.addEventListener(“click”, ()=> {

  Notification.requestPermission().then(perm => {

    if(perm === ‘granted’) {

      new Notification(“Example notification”)

    }

  })

})

Click on the button, and you’ll get a push notification in the bottom right corner of your web browser with the specified text.

This is the most basic way to create notifications, and it works on your phone as well as on your computer. Let’s look at some advanced notification properties.

Advanced Notifications Properties

In addition to the notification title, you can also pass an options argument to the constructor when creating the notification object. This options argument must be an object. Here, you can add several options to customize your notification.

The body Property

The first property you should know is body property. You’d use this to add a body to your notification, typically to convey more information in the form of text. Here’s a simple example:

const button = document.querySelector(‘button’)

button.addEventListener(“click”, ()=> {

  Notification.requestPermission().then(perm => {

    if(perm === ‘granted’) {

      new Notification(“Example notification”, {

       body: “This is more text”,

     })

    }

  })

})

If you run this code, the body text will show in the push notification, under the Example notification header.

The data Attribute

Often times you might want to add custom data to notifications. Maybe you want to display a particular error message if permission is denied, or store data you received from an API. For all such cases, you can use the data property to add custom data to your notification.

button.addEventListener(“click”, ()=> {

  Notification.requestPermission().then(perm => {

    if(perm === ‘granted’) {

      const notification = new Notification(“Example notification”, {

       body: “This is more text”,

       data: {hello: “world”}

     })

    

     alert(notification.data.hello)

    }

  })

})

You can access the data from the data property similarly to as shown in the above code block (inside the alert()).

You can also bind event listeners to your notifications. For example, the following event listener executes whenever you close the push notification. The callback function simply logs the custom message.

const notification = new Notification(“Example notification”, {

  body: “This is more text”,

  data: {hello: “world”}

})

notification. addEventListener(“close”, e => {

  console.log(e.target.data.hello)

})

This is an excellent way to pass data around if you need to do something when someone closes a notification or clicks on it. Apart from the close event (which executes when you close the notification), you should keep these event listeners in your mind:

  • show: Executes when the notification shows.
  • click: Executes when the user clicks anywhere in the notification.
  • error: Executes when you deny JavaScript permission to send notifications.
  • The icon Property

    The icon property is for adding an icon to the push notification. Assuming you have an icon logo named logo.png in the current directory, you can use it in your notifications like so:

    const notification = new Notification(“Example notification”, {

      icon: “logo.png”

    })

    If you’re struggling to link to your files, you need to understand the working of relative URLs and absolute URLs.

    When you save the file, refresh the browser, and click the button, the notification will have the image displayed on the left-hand side of the header and body.

    The tag Attribute

    When you set the tag attribute in your notification, you’re basically giving the notification a unique ID. Two notifications cannot exist together if they have the same tag. Instead, the newest notification will overwrite the older notification.

    Consider our previous button example (without a tag). If you were to click the button three times in quick succession, the three notifications will appear, and they’ll stack on top of one another. Now let’s say you added the following tag to the notification:

    const notification = new Notification(“Example notification”, {

      body: “This is more text”,

      tag: “My new tag”

    })

    If you were to click the button again, only one notification box will appear. Every subsequent click will overwrite the prior notification, so only one notification will show no matter how many times you click the button. This is useful if you want to add dynamic data (like Math.random()) to the body:

    const notification = new Notification(“Example notification”, {

      body: Math.random()

      icon: “logo.png”,

      tag: “My body tag”

    })

    Every time you click the button, a new number will appear. Use the tag property if you want to overwrite a current notification with new information inside of it. In a messaging app, for example, you can use the tag attribute to overwrite the notification with new messages.

    An Example of Push Notification Using JavaScript

    The following example detects anytime you lose focus on your page (i.e. when you close the page or open a new tab). In this case, the code sends a notification asking you to return:

    let notification

    document.addEventListener(“visibility-change”, ()=> {

      if(document.visibilityState === “hidden”) {

        notification = new Notification(“Come back please”, {

          body: “Don’t leave just yet :(“

          tag: “Come Back”

        })

      } else {

        notification.close()

      }

    })

    Whenever you lose focus on that page, you’ll get a notification asking you to come back to the page. But once you return to the page, the else block executes, which closes the push notification. This technique is excellent in situations where you want to give the user some kind of information after leaving your page.

    Learn More About JavaScript

    Event notification is just one of the numerous features you can find in JavaScript. In order to be really good with notifications, you must first grasp the fundamental language features and syntax of JavaScript. Building simple games is one of the ways through which you can boost your skills and familiarize yourself with the basic concepts of the language.

    Leave a Reply