chrome.notifications
API 可讓您使用範本建立通知,並在使用者的系統匣中向使用者顯示這些通知:
廣告外觀
複合式通知有四種不同版本:基本、圖片、清單和進度。所有通知都包含標題、訊息、通知訊息左側顯示的小圖示,以及 contextMessage
欄位 (以較淺的字型顯示第三個文字欄位)。
基本通知:
清單通知會顯示任意數量的清單項目:
圖片通知包含圖片預覽:
進度通知會顯示進度列:
行為方式
在 ChromeOS 中,通知會顯示在使用者的系統匣中,然後留在系統匣內,直到使用者關閉為止。系統匣會記錄所有新通知的數量。使用者在系統匣中看到通知後,就會重設為零。
通知的優先順序可介於 -2 至 2 之間。優先順序小於 0 會顯示在 ChromeOS 通知中心,因為其他平台則會發生錯誤。預設優先順序為 0。優先順序大於 0 時,系統會顯示時間大於 0,而優先順序較高的通知則可顯示在系統匣中。
priority
設定不會影響 macOS 中的通知順序。
除了顯示資訊之外,所有通知類型最多可以包含兩個操作項目。當使用者點選操作項目時,您的擴充功能可以採取適當的操作回應。舉例來說,當使用者點選「Reply」(回覆) 後,電子郵件應用程式就會開啟,使用者則可完成回覆:
如何開發
如要使用這個 API,請呼叫 notifications.create()
方法,並使用 options
參數傳入通知詳細資料:
await chrome.notifications.create(id, options);
notifications.NotificationOptions
必須包含 notifications.TemplateType
,用於定義可用的通知詳細資料,以及這些詳細資料的顯示方式。
建立基本通知
所有範本類型 (basic
、image
、list
和 progress
) 都必須包含通知 title
和 message
,以及 iconUrl
,這是顯示在通知訊息左側顯示的小圖示連結。
以下是 basic
範本的範例:
var opt = {
type: "basic",
title: "Primary Title",
message: "Primary message to display",
iconUrl: "url_to_small_icon"
}
使用圖片
image
範本類型也包含 imageUrl
,這是在通知中預覽的圖片連結。請注意,macOS 使用者不會看到圖片。
var opt = {
type: "image",
title: "Primary Title",
message: "Primary message to display",
iconUrl: "url_to_small_icon",
imageUrl: "url_to_preview_image"
}
建立清單通知
list
範本會以清單格式顯示 items
。請注意,macOS 使用者只會看到第一個項目。
var opt = {
type: "list",
title: "Primary Title",
message: "Primary message to display",
iconUrl: "url_to_small_icon",
items: [{ title: "Item1", message: "This is item 1."},
{ title: "Item2", message: "This is item 2."},
{ title: "Item3", message: "This is item 3."}]
}```
### Create progress notification {: #progress }
The `progress` template displays a progress bar where current progress ranges from 0 to 100. On macOS the progress bar displays as a percentage value in the notification title instead of in the progress bar.
```js
var opt = {
type: "progress",
title: "Primary Title",
message: "Primary message to display",
iconUrl: "url_to_small_icon",
progress: 42
}
監聽及回應事件
所有通知都可以包含事件監聽器和事件處理常式,用於回應使用者動作 (請參閱 chrome.events
)。例如,您可以編寫事件處理常式來回應 notifications.onButtonClicked
事件。
事件監聽器:
chrome.notifications.onButtonClicked.addListener(replyBtnClick);
事件處理常式:
function replyBtnClick {
//Write function to respond to user action.
}
請考慮在 Service Worker 中加入事件監聽器和處理常式,這樣即使擴充功能並未執行,通知仍會彈出。