Show Desktop Notifications with JavaScript in the Browser

OpenJavaScript 0

Last updated: February 5, 2023.

Using the Notifications API, you can display notification to a user that appears at the system level (outside the browser).

First, you want should check whether the Notification API is supported in a user’s browser. The following code only runs a notify() function is it is found on the global window object:

if ("Notification" in window) {    
    notify();
} else {
    console.error("Browser does not support notifications");
}

If the Notification API is supported, then the notify() function below will run.

An important feature of the Noficiations API is that in order to prevent abuse, overuse and/or unwanted spamming, user permission is required to display notifications.

You ask for permission by calling Notification.requestPermission(), which returns a promise object. The return value of the promise provides information about the user’s decision regarding permission.

Before doing so, you can check whether permission has been granted previously by querying the value of Notification.permission:

// Possible permission values:
// 'granted': The user granted permission
// 'denied' The user rejected notification
// 'default' No response from user (as if defined but permission may be asked for again)

if (Notification.permission === "granted") {
    notify(); // Runs notify function because permission was already granted
} else {
    Notification.requestPermission().then(res => {
    // Requests permission
        if (res === "granted") {
            notify(); // Runs notify because permission was granted
        } else {
            console.error("Did not receive permission for notifications");
        }
    })
}

You are only able to display notification to the user if the value of asking returns 'granted' or it has been given previously and remembered.

If a user denies permission, the browser will rememebr this user decision and is unlikely to ask the user again when prompted , at least for some time.

Displaying a notification

If permission is granted, you can display a new notification to the user by creating a new instance of a Notification object, passing in first a header text for the notificaiton and then an options object:

const notification = new Notification('Breaking:', {

    body: `Celebrity Caught in Fresh Scandal`,

    icon: 'https://unsplash.it/400/400',

    vibration: [200, 100, 200] // Vibration pattern in milliseconds (only for supporting hardware)

});

If you store a reference to the notification when creating it (notification above), you can then call some useful methods on this reference:

setTimeout(() => { notification.close() }, 10*1000);
// Closes notification after 10 seconds

notification.addEventListener('click', () => {

  window.open('https://openjavascript.info', '_blank');

});
// Navigates to a URL when clicked

You can send more than one notification to a user by creating multiple Notification objects.

However, how these will be displayed (e.g. one after another or simulatenously) varies by browser and system.

Complete example

if ("Notification" in window) {
    if (Notification.permission === "granted") {
        notify();
    } else {
        Notification.requestPermission().then(res => {
            if (res === "granted") {
                notify();
            } else {
                console.error("Did not receive permission for notifications");
            }
        })
    }
} else {
    console.error("Browser does not support notifications");
}

function notify() {

    const notification = new Notification('Breaking:',{
        body: `Celebrity Caught in Fresh Scandal`,
        icon: 'https://unsplash.it/400/400',
        vibration: [300,200,300],
    });

    notification.addEventListener('click', function() {
        window.open('https://www.openjavascript.info');
    });

    setTimeout(() => notification.close(), 5*1000);

}

Related posts