使用丰富的桌面通知通知用户发生了重要的事情。通知显示在浏览器窗口之外。如以下快照所示,通知的外观和显示位置的详细信息取决于平台。
您可以使用一些 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 的通知教程。忽略与权限相关的代码;如果您声明“通知”权限,则无需这样做。