用網頁版 Gmail 時,新郵件送達會在螢幕右下角跳出提示框。這個效果並不依賴任何外掛——HTML5 的 Notification API 就能做到。
動手之前,建議先到 caniuse 查一下目標瀏覽器對 Notification API 的支援度。與其寫完才發現整個 API 根本不能用,不如花一分鐘先確認。
var notification = new Notification('Notification Title', {
body: 'Your Message'
});
建構子的第一個參數是標題,第二個是 options 物件,可用的屬性有:
通知不會自己跳出來,必須先取得使用者授權。 requestPermission 的回呼會收到三種結果之一:
Notification.requestPermission(function(permission) {
// 在這裡建立通知
});
<button id="button">Read your notification</button>
#button {
font-size: 1.1rem;
width: 200px;
height: 60px;
border: 2px solid #df7813;
border-radius: 20px / 50px;
background: #fff;
color: #df7813;
}
#button:hover {
background: #df7813;
color: #fff;
transition: 0.4s ease;
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('button').addEventListener('click', function() {
if (!('Notification' in window)) {
alert('Sorry bro, your browser is not good enough to display notification');
return;
}
Notification.requestPermission(function(permission) {
var config = {
body: 'Thanks for clicking that button. Hope you liked.',
icon: 'https://cdn2.iconfinder.com/data/icons/ios-7-style-metro-ui-icons/512/MetroUI_HTML5.png',
dir: 'auto'
};
var notification = new Notification("Here I am!", config);
});
});
});
這裡刻意把權限請求放在點擊事件裡——多數瀏覽器要求通知授權必須由使用者互動觸發,直接在頁面載入時跳出請求容易被忽略或被瀏覽器攔下。
要求使用者手動關掉通知是很糟糕的體驗。用 setTimeout 定時關閉即可:
var config = {
body: 'Today too many guys got eyes on me, you did the same thing. Thanks',
icon: 'icon.png',
dir: 'auto'
};
var notification = new Notification("Here I am!", config);
setTimeout(function() {
notification.close();
}, 5000);
想更深入理解這個 API,可以參考 MDN 上的說明文件與 Paul Lund 撰寫的 Notification API 教學;CodePen 上也有 Prakash(@imprakash)做的 demo 可以直接把玩。