您现在的位置:油猴 > 油猴插件 > tampermonkey手机版 > 正文
Chrome浏览器扩展开发系列之十:桌面通知Notificationchrome插件开发
http://tampermonkeya.com/      2022/4/11 0:04:28      作者:tampermonkey
桌面通知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。 通知必须获得用户的授权才能够显示,从而避免非用户期望的通知干扰用户。对通知的授权有三种,分别由字符串”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 grantedelse if (Notification.permission === "granted") {// If it's okay let's create a notificationnew Notification("Granted!");}// Otherwise, ask the user for permissionelse if (Notification.permission !== 'denied') {Notification.requestPermission(function (permission) {// If the user accepts, let's create a notificationif (permission === "granted") {new Notification("Request granted!");}});}}Chrome浏览器的chrome.notifications.* API能够基于模板创建桌面通知,并在操作系统右下角的托盘中显示通知。要在Chrome浏览器扩展中使用通知,首先要在manifest.json文件中声明notifications的权限如下:{"permissions": ["notifications"],}chrome.notifications.TemplateType是枚举类型,枚举值如下: chrome.notifications. PermissionLevel是枚举类型,枚举值如下: chrome.notifications.NotificationOptions对象的属性如下: chrome.notifications API中的常用方法:1、 创建并显示通知chrome.notifications.create(string notificationId,NotificationOptions options,function(string notificationId) {...})其中属性说明如下: 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