Desktop Notification也稱為Web Notification,是在Web頁面之外,以彈出案頭對話方塊的形式通知使用者發生了某事件。Web Notification於2015.9.10成為W3C推薦標準,網址https://www.w3.org/TR/notifications/。每個通知對話方塊都包括title, direction, language和origin。通知對話方塊還可以有body, tag, icon URL和icon image。
通知必須獲得使用者的授權才能夠顯示,從而避免非使用者期望的通知幹擾使用者。對通知的授權有三種,分別由字串”default”(使用者未顯式授權,同denied), ”denied”, ”granted”表示。
由於通知的顯示與瀏覽器的實現有關,與使用者的授權有關,所以在使用案頭通知之前,往往要檢查瀏覽器和使用者的授權,樣本如下:
function checkNotification(){
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
}
// check whether notification permissions have alredy been granted
else if (Notification.permission === "granted") {
// If it's okay let's create a notification
new Notification("Granted!");
}
// Otherwise, ask the user for permission
else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
// If the user accepts, let's create a notification
if (permission === "granted") {
new Notification("Request granted!");
}
});
}
}
Chrome瀏覽器的chrome.notifications.* API能夠基於模板建立案頭通知,並在作業系統右下角的托盤中顯示通知。
要在Chrome瀏覽器延伸中使用通知,首先要在manifest.json檔案中聲明notifications的許可權如下:
{
"permissions": [
"notifications"
],
}
chrome.notifications.TemplateType是枚舉類型,枚舉值如下:
| 枚舉值 |
注釋 |
| "basic" |
預設範本 icon, title, message, expandedMessage位於兩個button之上 |
| "image" |
icon, title, message, expandedMessage, image位於兩個button之上 |
| "list" |
icon, title, message, items位於兩個button之上 |
| "progress" |
icon, title, message, progress位於兩個button之上 |
chrome.notifications. PermissionLevel是枚舉類型,枚舉值如下:
| 枚舉值 |
注釋 |
| "granted" |
預設值,使用者授權顯示通知 |
| "denied" |
使用者未授權顯示通知 |
chrome.notifications.NotificationOptions對象的屬性如下:
| 屬性名稱 |
類型 |
必選/可選 |
注釋 |
| type |
TemplateType |
可選 |
通知的類型, chrome.notifications.create()建立通知時必選 |
| title |
string |
可選 |
通知的標題, chrome.notifications.create()建立通知時必選 |
| message |
string |
可選 |
通知的主體內容, chrome.notifications.create()建立通知時必選 |
| contextMessage |
string |
可選 |
通知的備選內容 |
| buttons |
array of object |
可選 |
該數組最多2個元素,分別代表2個button。 每個button對象都有title和iconUrl兩個屬性(string類型),其中iconUrl屬性可選 |
| appIconMaskUrl |
string |
可選 |
應用表徵圖URL的掩碼,用以規範URL |
| iconUrl |
string |
可選 |
表徵圖的URL |
| imageUrl |
string |
可選 |
"image"類型的通知的圖片的URL |
| priority |
integer |
可選 |
優先順序,有效範圍[-2,2],預設0 |
| eventTime |
double |
可選 |
通知的時間戳記,單位ms |
| items |
array of object |
可選 |
該數組中的每個元素代表一個通知。 每個通知對象都有title和message兩個屬性(string類型) |
| progress |
integer |
可選 |
當前的進度,有效範圍[0,100] |
| isClickable |
boolean |
可選 |
通知視窗是否響應點擊事件 |
chrome.notifications API中的常用方法:
· 建立並顯示通知
chrome.notifications.create(
string notificationId,
NotificationOptions options,
function(string notificationId) {...}
)
其中屬性說明如下:
| 屬性名稱 |
類型 |
必選/可選 |
注釋 |
| notificationId |
string |
可選 |
通知的標識符。 如果未設定或設定為””,則自動產生唯一識別碼; 如果設定的值與已有的通知相同,則替換已有的通知 |
| options |
NotificationOptions |
必選 |
|