選單
GSS 技術部落格
在這個園地裡我們將從技術、專案管理、客戶對談面和大家分享我們多年的經驗,希望大家不管是喜歡或是有意見,都可以回饋給我們,讓我們有機會和大家對話並一起成長!
若有任何問題請來信:gss_crm@gss.com.tw
2 分鐘閱讀時間 (405 個字)

[JavaScript] 裝置通知

unsplash-coding104

上週在優化功能時,想說加個通知,
於是就去找了一下 Desktop Notification 的作法。

發現真的超級簡單,只要兩個步驟, 下面用 React 做示範:

 [第一步] 要求權限: Notification.requestPermission

在發送通知前,
要先跟使用者要求通知的權限。 (如上圖)

// 要求權限
Notification.requestPermission();

// 或 在要求權限後執行 callback
Notification.requestPermission()
	.then((permission: 'denied' | 'granted') => {
		// do something here	
	}); 


一般是在載入頁面時 (我是使用 useEffect),
呼叫 Notification.requestPermission 去要求權限。

useEffect(() => {
	// 確定瀏覽器是否支援 Notification
  if (("Notification" in window)) {
		// 要求權限
		Notification.requestPermission();
  }
}, []) 

 [第二步] 發送通知: Notification

 發送通知的方式很簡單,就是建立一個通知實例:

// 發送文字通知
var notification = new Notification(title);

// 或 加上設定
notification = new Notification(title, options);

// 不需要使用後可以清除通知
notification.close(); 

 常用的 Options 屬性

  • body (string) 標題底下的文字內容
  • icon (string) 通知左側小圖 url
  • image (string) 通知上方大圖 url
  • vibrate (number[]) 震動方式 ([ 震動秒數, 停止秒數, 震動秒數, ...依此類推 ])
  • requireInteraction (boolean) 是否需要手動關閉通知,啟用會在下方多一個關閉鈕。預設值 false。
  • silent (boolean) 是否靜音,預設值 false。
  • tag (string) 通知的標籤,同一時間每個標籤只會顯示一則通知。
  • renotify (boolean) 新通知取代舊通知時,是否通知使用者。和上面的 tag 是一組的。預設值 false。
更多屬性可以參考文件:
...

Notification() - Web APIs | MDN

The Notification() constructor creates a new Notification object instance, which represents a user notification.

 通知的事件

通知實例可以設定的事件 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
} 
Java Concurrency #4 - Sharing Objects[1]
[CSS] Safari 的坑: 100vh

相關文章

 

評論

尚無評論
已經注冊了? 這裡登入
Guest
2024/05/06, 週一

Captcha 圖像