用網頁版 Gmail 時,新郵件進來,右下角會滑出一個提示框。這個「跳出瀏覽器視窗之外」的通知,靠的是 HTML5 的 Notification API,實作難度比想像中低得多。
如果你鎖定特定版本的瀏覽器,第一步請先去 caniuse 查一下 Notification API 的支援度,別把寶貴時間花在根本跑不起來的 API 上。程式碼裡也該做防禦:判斷 window 上你有沒有 Notification 這個物件,沒有的話就退回其他提示方式。
另外一個實務前提:通知權限屬於敏感能力,正式環境通常需要 HTTPS(localhost 例外),且必須由使用者操作觸發,不能在頁面載入時就自動跳出來索取權限。
var notification = new Notification('Notification Title', {
body: 'Your Message'
});
建構子的第一個參數是標題,第二個是 options 物件,可以設定:
實務上 icon 建議準備一張清晰的方形圖,並確認它來自你的站台或 CORS 友善的來源,否則可能顯示不出來。
顯示通知之前,必須先向使用者請求授權。requestPermission 會回傳三種狀態之一:
Notification.requestPermission(function(permission) {
// 唯有 granted 時才建立 Notification
});
HTML 很單純:
<button id="button">Read your notification</button>
CSS 稍微修一下,讓按鈕看得過去:
#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);
});
});
});
流程是:點擊 → 檢查 API 是否存在 → 請求權限 → 使用者同意後才建立通知。把 requestPermission 放在點擊事件裡,而不放在頁面載入時,是為了符合瀏覽器對使用者手勢的要求,也比較不會讓使用者反感。
一直留在畫面上等使用者手動關掉,體驗並不好。用 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);
五秒是一個常見的折衷:夠使用者讀完一行訊息,又不至於佔著畫面太久。訊息較長時記得調大,或直接讓使用者自行關閉。