Do you know JavaScript Notification?

Do you know JavaScript Notification?

Table of Contents

Notifications API

Javascript Notification API lets you send notifications to the end users. This feature is only available in HTTPS*. The messages are displayed even when the user has switched tabs or moved to a different app.

It also works with localhost lets do it.

Create a Button

Let’s add a button with a class notification. Clicking the button will eventually trigger the Javascript Notification API

<button class="notification"> Notify Me <button>

Event Listener

let’s start with an event listener, which will console.log a message when the button is clicked.

const NotificationBtn = document.queryselector(".notification");
const requestpermission = function(){
console.log("Button clicked")
};
Notification.addEventListener("click", requestpremission);

Improve Function

Improve the function by checking if the browser has Notification API support. Next is to check for permission if the end-user has allowed notifications.

const requestpermission = function(){
if (!("Notification" in window))
throw new Error("Browser doesn't support Notification");
Notificatoin.requestpermission().then((permission) = {
console.log(permission)
});
};

Complete Code

Lastly, add notification using Notification API where the first argument is the title and the second (object) are other options.

const NotificationBtn = document.queryselector(".notification");

const requestpermission = function(){
if (!("Notification" in window))
  throw new Error("Browser doesn't support Notification");
Notificatoin.requestpermission().then((permission) = {
    const notification= new notification("Test", {
    body: "This is test Notification", 
    icon: "./notification.png",
  });
 });
};

NotificationBtn.addEventListener("click", requestpermission);

10+ JavaScript Projects with Source Code