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 对象替换为自己的对象,该对象充当具有添加行为的代理(在创建新通知时调用回调).
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屋!