上週在優化功能時,想說加個通知,
於是就去找了一下 Desktop Notification 的作法。
發現真的超級簡單,只要兩個步驟, 下面用 React 做示範:
在發送通知前,
要先跟使用者要求通知的權限。 (如上圖)
// 要求權限 Notification.requestPermission(); // 或 在要求權限後執行 callback Notification.requestPermission() .then((permission: 'denied' | 'granted') => { // do something here });
一般是在載入頁面時 (我是使用 useEffect),
呼叫 Notification.requestPermission 去要求權限。
useEffect(() => { // 確定瀏覽器是否支援 Notification if (("Notification" in window)) { // 要求權限 Notification.requestPermission(); } }, [])
發送通知的方式很簡單,就是建立一個通知實例:
// 發送文字通知 var notification = new Notification(title); // 或 加上設定 notification = new Notification(title, options); // 不需要使用後可以清除通知 notification.close();
通知實例可以設定的事件 handler:
var notification = new Notification(title); // 設定通知的點擊事件 notification.onclick = event => { // do something here } // 設定通知的顯示事件 notification.onshow = event => { // do something here } // 設定通知的關閉事件 notification.onclose = event => { // do something here } // 設定通知的錯誤事件 notification.onerror = event => { // do something here }