透過豐富的桌面通知,通知使用者有重大發生。通知會顯示在瀏覽器視窗外。下列快照顯示了通知外觀及顯示位置的詳細資料,取決於平台。
您會使用一些 JavaScript 來建立通知視窗,並視需要使用封裝在擴充功能中的 HTML 頁面。
範例
首先,請在資訊清單中宣告 notifications
權限:
{
"name": "My extension",
"manifest_version": 2,
...
"permissions": [
"notifications"
],
...
// Note: Because of bug 134315, you must declare any images you
// want to use with createNotification() as a web accessible resource.
"web_accessible_resources": [
"48.png"
],
}
接著,使用 webkitNotifications
物件建立通知:
// Note: There's no need to call webkitNotifications.checkPermission().
// Extensions that declare the notifications permission are always
// allowed create notifications.
// Create a simple text notification:
var notification = webkitNotifications.createNotification(
'48.png', // icon url - can be relative
'Hello!', // notification title
'Lorem ipsum...' // notification body text
);
// Or create an HTML notification:
var notification = webkitNotifications.createHTMLNotification(
'notification.html' // html url - can be relative
);
// Then show the notification.
notification.show();
API 參考資料
請參閱桌面通知草稿規格。
與其他檢視畫面通訊
您可以使用 extension.getBackgroundPage 和 extension.getViews,在通知和擴充功能中的其他檢視畫面之間進行通訊。例如:
chrome.extension.getBackgroundPage().doThing();
chrome.extension.getViews({type:"notification"}).forEach(function(win) {
win.doOtherThing();
});
其他示例
您可以在 examples/api/notifications 目錄中找到使用通知的簡單範例。如需查看原始碼的其他範例,並取得查看原始碼的相關說明,請參閱範例。
另請參閱 html5rocks.com 的通知教學課程。忽略權限相關程式碼;如果您宣告「通知」權限,就不需要這麼做。