gauge
gauge

Reputation: 1313

Event Listener for Web Notification

Is there a way to set an event listener for a desktop notification?

document.addEventListener("desktop notification", function(){
    // do something
});

I've looked through the MDN event reference, but the only event type for a notification seems to be only for alert().

Upvotes: 4

Views: 12143

Answers (2)

deksden
deksden

Reputation: 774

See https://github.com/jiahaog/nativefier project for working sample. Notice snippet (source from https://github.com/jiahaog/nativefier/blob/development/app/src/static/preload.js):

function setNotificationCallback(callback) {

    const OldNotify = window.Notification;
    const newNotify = (title, opt) => {
        callback(title, opt);
        return new OldNotify(title, opt);
    };
    newNotify.requestPermission = OldNotify.requestPermission.bind(OldNotify);
    Object.defineProperty(newNotify, 'permission', {
        get: () => {
            return OldNotify.permission;
        }
    });

    window.Notification = newNotify;
}

So, you replace window's Notification object with own object that act as a proxy with added behaviour (calling callback on creating new Notification).

Hope this helps

Upvotes: 9

vorillaz
vorillaz

Reputation: 6266

@marekful is right. Instead of placing global event listeners, you may consider placing a callback or even attach an event on the Notification object.

var noticeMe = new Notification(title, options); 
noticeMe.onshow = function() { console.log("easy!") };

A full list of supported events may be found here: https://developer.mozilla.org/en-US/docs/Web/API/Notification, Also here is an article I wrote a few months back about the Notification API

Take a look at

Upvotes: 1

Related Questions