Event Listener for Web Notification

后端 未结 2 1849
感动是毒
感动是毒 2021-01-07 08:15

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

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


        
2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-07 08:50

    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

提交回复
热议问题