HTML5桌面通知
HTML5桌面通知
桌面通知是H5新增的技术,除IE外,其余现代浏览器基本支持
- 基本用法
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button type="button">点击推送</button>
<script>
var btn = document.getElementsByTagName('button')[0]
btn.addEventListener('click',function(){
var n = new Notification('桌面推送',{
body:'我是推送的内容',
icon: './img/logo.png',
image: './img/下载.jpg'
})
})
</script>
</body>
</html>
如果将此html文件直接在浏览器中打开,点击推送按钮将没有反应,这是因为消息通知只有通过web服务访问该页面的时候才会生效,所有我们的文件需要使用服务器的形式打开

- 比较完整的代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button>发起通知</button>
<script>
window.addEventListener("load",function(){
// 判断是否有通知权限,如果没有就请求获得权限
if(window.Notification && Notification.permission !== "granted"){
Notification.requestPermission(function(status){
if(Notification.permission !== status){
Notification.permission = status
}
})
}
var button = document.getElementsByTagName('button')[0]
button.addEventListener('click',function(){
// 如果用户同意就建立一个通知
if(window.Notification && Notification.permission === 'granted'){
var n = new Notification("hi!")
}
// 如果用户没有选择是否显示通知
else if(window.Notification && Notification.permission !== 'denied'){
Notification.requestPermission(function(status){
if(Notification.permission !== status){
Notification.permission = status
}
// 如果用户同意了
if(status === 'granted'){
var n = new Notification("hi!")
}
// 否则,我们可以让步的使用常规模态的 alert
else{
alert("Hi!");
}
})
}
// 如果用户拒绝接受通知
else {
// 我们可以让步的使用常规模态的 alert
alert("Hi!");
}
})
})
</script>
</body>
</html>

浙公网安备 33010602011771号