Chrome浏览器扩展开发系列之十:桌面通知Notification

发布时间: 编辑:RILL 0人评论 14747次浏览 chrome插件开发
摘要 : Chrome浏览器扩展开发系列之十:桌面通知Notification

桌面通知Notification

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。

桌面通知Notification
通知必须获得用户的授权才能够显示,从而避免非用户期望的通知干扰用户。对通知的授权有三种,分别由字符串”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是枚举类型,枚举值如下:
chrome.notifications.TemplateType的枚举值

chrome.notifications. PermissionLevel是枚举类型,枚举值如下:

chrome.notifications. PermissionLevel的枚举值

chrome.notifications.NotificationOptions对象的属性如下:

chrome.notifications.NotificationOptions对象的属性

chrome.notifications API中的常用方法:
1、 创建并显示通知
chrome.notifications.create(
string notificationId,
NotificationOptions options,
function(string notificationId) {...}
)
其中属性说明如下:
chrome.notifications创建并显示通知的属性说明

2、 更新已有的通知
chrome.notifications.update(
string notificationId,
NotificationOptions options,
function (boolean wasUpdated) {...}
)
其中属性与create()类似。
3、清除指定的通知
chrome.notifications.clear(string notificationId, function(boolean wasCleared) {...})
4、获取所有通知
chrome.notifications.getAll(function(object notifications) {...})


最后介绍Chrome扩展中background与notification之间的互操作问题。

在处理通知的JavaScript脚本文件中,可以访问background页面的方法如下:
chrome.extension.getBackgroundPage().doThing();
在background页面的JavaScript脚本文件中,可以访问通知的JavaScript脚本文件中的方法如下:
chrome.extension.getViews({type:"notification"}).forEach(function(notificationWindow) {
notificationWindow.doOtherThing();
});

文章转自:https://www.cnblogs.com/champagne/p/4831874.html

查看更多

转载必须注明来自:https://huajiakeji.com/dev/2019-01/1783.html

30 Seconds of Knowledge

30 Seconds of Knowledge

0 人评论 9195 次人浏览 4.0分 4.0 分
30 Seconds of Knowledge Chrome学习插件,每次打开新标签页时,Google Chrome扩展程序都可以让你获得新的开发人员技能。
评论:(0)

已有 0 位网友发表了一针见血的评论,你还等什么?