前几天要作一个桌面通知的功能,翻查之前作的笔记,发现 webkitNotifications
这个已经不能用了,baidu了下,基本都是介绍webkitNotifications
的,后来在SOF上找到答案,如今chrome支持的是Notification
,估计是W3C标准化了。api也变了,mark之。javascript
title: "别动神仙说: "
body: "这里是body"
icon: "http://q4.qlogo.cn/g?b=qq&k=icUjVAN5Ja7BCDQ1ICl8Svw&s=40"
tag: "1" // 通知框ID,相同id可替换,而不是出现新的通知框
lang: "" // 语言
dir: "auto" // 文字方向java
new Notification('别动神仙说:', { body: '这里是body', icon: 'http://q4.qlogo.cn/g?b=qq&k=icUjVAN5Ja7BCDQ1ICl8Svw&s=40', tag: 1 });
onshow: null // 显示通知框时调用
onclick: null // 点击通知框时调用
onclose: null // 点击通知框关闭按钮时调用
onerror: nullweb
例如实现通知弹出一段时间后自动关闭chrome
var notification = new Notification('标题'); notification.onshow = function () { setTimeout(function () { notification.close(); }, 3000); }
Notification.permission
有三种状态segmentfault
default
:未设置过为这个状态,经过Notification.requestPermission()能够询问用户是否容许通知granted
:用户点击容许后的状态denied
: 用户点击拒绝后的状态,通知框不可用
Notification.requestPermission()
通常在Notification.permission === 'default'时,用户经过点击等操做调用api
document.onclick = function() { Notification.requestPermission() }
使用回调spa
Notification.requestPermission(function (permission) { // 可在确认后直接弹出 if (permission === 'granted') { var notification = new Notification('弹窗'); } });
Notification.close()
通知框关闭code
function notify() { if (!("Notification" in window)) { alert("This browser does not support desktop notification"); return; } if (Notification.permission === "granted") { var notification = new Notification("Hi there!"); } else if (Notification.permission === 'default') { Notification.requestPermission(function (permission) { if (permission === "granted") { var notification = new Notification("Hi there!"); } }); } }
https://developer.mozilla.org/en-US/docs/Web/API/Notification.tagip