Physical Address
Godawari 2 Attariya Kailali
Physical Address
Godawari 2 Attariya Kailali
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.
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>
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 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)
});
};
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