HTML5之Notification简单使用

时间:2023-03-09 01:42:21
HTML5之Notification简单使用
var webNotification = {
init: function() {
if(!this.isSupport()) {
console.log('不支持通知');
return;
}
this.initElement();
this.initPermission();
},
isSupport: function() {
return !!window.Notification;
},
element: null,
isPermission: false,
initElement: function() {
var element = document.createElement('button');
element.type = 'button';
element.style = 'position: absolute;top: -100px;';
element.onclick = function() {
Notification.requestPermission(function(result) {
console.log('result:' + result);
if(result === 'granted') {
this.isPermission = true;
} else {
this.isPermission = false;
}
}.bind(this));
}.bind(this);
document.body.appendChild(element);
this.element = element;
},
initPermission: function() {
this.element.click();
},
notify: function(title, options, clickCallback, closeCallback) {
var notification = new Notification(title, options);
notification.onclick = clickCallback;
notification.onclose = closeCallback;
return notification;
}
};

初始化

webNotification.init();

测试

webNotification.notify('我是标题', {
body: '我是通知内容',
icon: '/favicon.ico',
}, function() {
alert('我点击了通知');
}, function() {
alert('我关闭了通知');
});