Display Desktop Notifications With ElectronJS

Display Desktop Notifications With ElectronJS

Quick post for a reminder on how to display desktop notification with ElectronJS. First you dont need to use node-notifier ElectronJS has it all built under the hood.

View the docs here.
https://www.electronjs.org/docs/latest/api/notification

There are some examples here.
https://www.electronjs.org/docs/latest/tutorial/notifications

I’ll just add to some points that are not listed in the docs.

!Important you first need to allow notifications when it presents you with this dialogue I clicked the cross which disables them.

You can re enable them through the notification centre on Mac under system preferences.

This is what I am using I needed mine to open an external linked after being clicked.

/**
 * Display a desktop app notification
 * @param {*} title 
 * @param {*} body 
 */
function showNotification(title, body, link) {
    if (Notification.isSupported()) {
        const notification = new Notification({
            title: title,
            //subtitle: '1Subtitle of the Notification',
            body: body
        });
        notification.addListener('click', () => {
            console.log('Notification is Clicked', link);
            require("electron").shell.openExternal(link);
        });

        notification.addListener('show', () => {
            console.log('Notification is shown');
        });
        notification.addListener('close', () => {
            console.log('Notification is Automatically Closed')
        });
        notification.show();
    }
}

Make sure you only open fire the notification function after the main process is ready.

Also inject the Notification dependancy in the electron js head.

const {
    app,
    ipcMain,
    BrowserWindow,
    Notification
} = require("electron");

Use it like this.

showNotification('Basic Notification', 'Notification from the Main process', 'https://example.com/browse/desktop-app');

Leave a comment

Your email address will not be published. Required fields are marked *