Web通知的事件监听器 [英] 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
});
我已经浏览了 MDN事件参考,但是通知的唯一事件类型似乎仅用于alert()
.
I've looked through the MDN event reference, but the only event type for a notification seems to be only for alert()
.
推荐答案
请参见 https://github.com/jiahaog/nativefier 项目以获取工作示例.注意片段(来自 https://github.com/jiahaog/nativefier/blob/development/app/src/static/preload.js ):
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;
}
因此,您将窗口的Notification对象替换为自己的对象,该对象充当具有增加的行为的代理(在创建新Notification时调用回调).
So, you replace window's Notification object with own object that act as a proxy with added behaviour (calling callback on creating new Notification).
希望这对您有帮助
这篇关于Web通知的事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!