前些天瀏覽網(wǎng)站的時(shí)候突然跳出個(gè)通知的允許與禁止蹬癌,覺得很有新穎還很有意思鳄哭,決定學(xué)習(xí)一下
了解得知這個(gè)是HTML5的消息通知機(jī)制notification
首先感謝以下文章幫助我少走了很多彎路
相信大家在看一些新聞宛官,視頻類的網(wǎng)站時(shí)會跳出一些通知

通知
當(dāng)授權(quán)后有時(shí)候會跳出推送的消息

通知消息
這些功能很多主流網(wǎng)站已經(jīng)在使用了挺勿,是時(shí)候好好學(xué)上一波了六水。
其實(shí)很簡單增炭,這玩意只需要對照notification這個(gè)接口即可烟阐。
在使用前查查是否是自己需要的搬俊,避免浪費(fèi)時(shí)間

notifacation兼容性
想要了解怎么使用,沒問題先把代碼復(fù)制跑一邊啥事都解決了蜒茄。
// html
<button id="btn">點(diǎn)擊</button>
// js
<script>
window.onload = function() {
//首先詢問用戶是否授權(quán)唉擂,只有授權(quán)后才能顯示 Notification.requestPermission()
var btn = document.getElementById('btn');
btn.addEventListener('click', function() {
var notification = new Notification("消息通知", {
noscreen: true,
dir: 'rtl',
body: '哈哈!酷檀葛!',
tag: '1',
icon: 'img/1.png',
renotify: true
})
var notification2 = new Notification("消息通知", {
noscreen: true,
dir: 'rtl',
body: '哈哈玩祟!酷!',
tag: '2',
icon: 'img/1.png',
renotify: true
})
var notification3 = new Notification("消息通知", {
noscreen: true,
dir: 'rtl',
body: '哈哈屿聋!酷空扎!',
tag: '3',
icon: 'img/1.png',
renotify: true
})
setInterval(function() {
notification.close()
console.log('關(guān)閉');
}, 5000)
notification.onclick = function() {
// alert('點(diǎn)擊了');
console.log('點(diǎn)擊了');
notification.close()
}
notification.onclose = function() {
// alert('已經(jīng)關(guān)閉藏鹊!');
console.log('已經(jīng)關(guān)閉');
}
notification.onshow = function() {
// alert('彈出前!');
console.log('彈出前');
}
})
}
</script>
以下幾個(gè)常用的API
//1.利用構(gòu)造函數(shù)來創(chuàng)建一個(gè)實(shí)例
var notification = new Notification(title, options)
/*
title
一定會被顯示的通知標(biāo)題
options 可選(常用转锈,更多需要查api)
一個(gè)被允許用來設(shè)置通知的對象盘寡。它包含以下屬性:
dir : 文字的方向;它的值可以是 auto(自動), ltr(從左到右), or rtl(從右到左)
body: 通知中額外顯示的字符串
tag: 賦予通知一個(gè)ID撮慨,以便在必要的時(shí)候?qū)νㄖM(jìn)行刷新竿痰、替換或移除。
icon: 一個(gè)圖片的URL砌溺,將被用于顯示通知的圖標(biāo)影涉。
*/
如何判斷用戶是否同意呢
Notification.permission
授權(quán)狀態(tài):denied (用戶拒絕了通知的顯示), granted (用戶允許了通知的顯示),默認(rèn) default (因?yàn)椴恢烙脩舻倪x擇,所以瀏覽器的行為與 denied 時(shí)相同).
發(fā)出一個(gè)通知后想要讓其點(diǎn)擊有效果
onclick:點(diǎn)擊時(shí)觸發(fā)
onshow:顯示通知時(shí)觸發(fā)
onclose:關(guān)閉通知時(shí)觸發(fā)
onerror:通知發(fā)生錯(cuò)誤時(shí)觸發(fā)
上方的小例子中有使用可看看规伐。