HTML5 Notification
Notification API的通知接口用于向用户配置和显示桌面通知。
生产环境仅支持https下使用;否则会被默认禁止。开发环境可以在localhost
或者127.0.0.1
下调用。
const notification = new Notification(title, options)
用来设置通知的对象。
dir
值包括auto(自动)
,ltr(从左到右)
,rtl(从右到左)
。lang
指定通知中所使用的语言。body
通知中额外显示的字符串。image
string,正文图片地址。tag
赋予通知一个ID,以便在必要的时候对通知进行刷新、替换或移除。icon
一个图片的URL,将被用于显示通知的图标。data
任意类型和通知相关联的数据;常用于方法的回调参数。timestamp
string,通知显示延迟时间。badge
当没有足够空间来显示通知本体时,用于表示通知的图像的URL。renotify
bool值,新通知出现是否替换之前的,true表示替换,否则队列显示。【chrome无明显效果,FF可以显示,见图1-1】silent
bool,通知出现的时候,是否静音;默认false。vibrate
通知显示的时候,设备震动,比如:[200, 100, 200]
表示震动200ms,然后停止100ms,然后再震动200ms。【设置此属性,silent必须为false,否则会抛出错误】sound
string,表示通知出现要播放的音频资源。【windows实测无效】noscreen
bool,是否不再屏幕上显示通知信息。默认false。sticky
bool,是否应该粘滞性,即不容易被用户清理。默认false。requireInteraction
bool,指定通知是否保持活性,知道用户点击或关闭;默认false。Notification.permission
只读属性。一个用于表明当前通知显示授权状态的字符串。
denied
用户拒绝显示通知granted
用户允许显示通知default
用户未授权操作,行为等同于deniedNotification.title
只读,获取构造方法中指定的title值。
以下属性类同。
Notification.dir
Notification.lang
Notification.body
Notification.tag
Notification.icon
Notification.onclick
处理click事件。当用户点击通知时被触发。
Notification.onshow
当通知显示的时候被触发。
Notification.onerror
当通知遇到错误时触发。
Notification.onclose
当用户关闭通知时触发。
Notification.requestPermission()
用于当前页面向用户申请显示通知的权限。
这个方法只能被用户行为调用,不能被其它方式调用。
Notification.close()
关闭通知。
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Notification</title>
</head>
<body>
<button onclick="notification.show()">有MM要加你为好友!</button>
<script type="text/javascript">
const NOTIFICATION_PERMISSION = Object.create(null, {
GRANTED: { value: 'granted' },
DENIED: { value: 'denied' },
DEFAULT: { value: 'default' }
});
const notification = {
show() {
if (!('Notification' in window)) {
console.warn('当前浏览器不支持!如果想加MM请立即升级浏览器!');
return;
}
if (Notification.permission !== NOTIFICATION_PERMISSION.GRANTED) {
// 未授权
this.permission();
return;
}
this.notify();
},
async permission() {
const permission = await Notification.requestPermission();
if (permission === NOTIFICATION_PERMISSION.GRANTED) {
this.notify();
return;
}
alert('您已拒绝MM好友邀请!');
},
notify() {
const notification = new Notification('Hi, 有MM想要加你为好友!', {
tag: Math.random().toString(16).substring(2, 8) + (+new Date()),
icon: './img/wxlogo.png',
body: '一位漂亮MM距离你0.01km,请接收她的好友邀请吧~',
image: './img/user-img-girl.jpg',
lang: 'zh-cmn-Hans',
sound: './audio/HOT PINK.mp3',
renotify: false,
silent: false,
vibrate: [300, 100, 200, 100, 100],
noscreen: false,
sticky: true,
requireInteraction: true
});
notification.onclick = function () {
console.log('用户点击了通知');
window.open('https://www.google.com');
};
notification.onshow = function () {
console.log('通知显示了');
};
notification.onclose = function () {
console.log('通知被关闭了');
};
setTimeout(() => {
notification.close();
}, 30000);
}
};
</script>
</body>
</html>
图4-1
图1-1
优质内容筛选与推荐>>