if (window.Notification) { window.location.hash += '浏览器支持通知
API'; } else { window.location.hash += '浏览器不支持通知 API';
}
window.Notification.requestPermission();
requestPermission() 只在用户显式触发事件,如单击按钮、点击鼠标或按下右键。
if (window.Notification) {
if (window.Notification.permission == 'granted') {
// 获取权限
} else if (window.Notification.permission == 'default') {
window.Notification.requestPermission();
}
} else {
window.location.hash += '浏览器不支持通知 API';
}
Notification 对象的 permission 属性包括 3 个值:
if (window.Notification) { if
(window.Notification.permission == 'granted') { // 获取权限
} else if (window.Notification.permission == 'default') {
window.Notification.requestPermission(); // 申请权限 }
var notification = new Notification(title, option); } else {
window.location.hash += '浏览器不支持通知 API';
}
var notification = new Notification(title, option);
该构造函数包括两个参数:第一个为通知的标题;第二个参数为一个对象,用于指定通知可以使用的各个选项,该对象可使用属性及属性值如下:
setTimeout(() => {
Notification.requestPermission(function (status) {
if ('granted' != status) return;
var notification = new Notification('好消息', {
dir: 'rtl',
lang: 'zh-CN',
icon: 'image/eessml.jpg',
body: '本站站长终于会 HTML 5 通知了',
});
});
}, 2000);
Notification 对象提供 4 个事件类型,用于检测通知。
setTimeout(() => {
Notification.requestPermission(function (status) {
if ('granted' != status) return;
var notification = new Notification('好消息', {
dir: 'rtl',
lang: 'zh-CN',
icon: 'image/eessml.jpg',
body: '本站站长终于会 HTML 5 通知了',
});
notification.onshow = function () {
location.hash = '来新的消息了';
};
notification.onclose = function () {
location.hash = '信息被关闭啦';
setTimeout(() => {
location.hash = '';
}, 500);
};
notification.onclick = function () {
location.hash = '你点消息啦';
setTimeout(() => {
window.open('https://lmssee.cn/image/lmssee.jpg', '_blank');
}, 500);
};
notification.onerror = function () {
location.hash = '消息出错了,站长有的忙了';
};
});
}, 2000);