3.4 桌面提醒
优质
小牛编辑
133浏览
2023-12-01
之前的章节提到过利用标题和badge向用户提供有限的信息,那么如果需要向用户提供更加丰富的信息怎么办呢?Chrome提供了桌面提醒功能,这个功能可以为用户提供更加丰富的信息。
桌面提醒,图片来自http://developer.chrome.com
要使用桌面提醒功能,需要在Manifest中声明notifications权限。
"permissions": [
"notifications"
]
创建桌面提醒非常容易,只需指定标题、内容和图片即可。下面的代码生成了标题为“Notification Demo”,内容为“Merry Christmas”,图片为“icon48.png”的桌面提醒窗口。
var notification = webkitNotifications.createNotification(
'icon48.png',
'Notification Demo',
'Merry Christmas'
);
桌面系统窗口创建之后是不会立刻显示出来的,为了让其显示,还要调用show方法
:
notification.show();
需要注意的是,对于要在桌面窗口中显示的图片,必须在Manifest的web_accessible_resources域中进行声明,否则会出现图片无法打开的情况:
"web_accessible_resources": [
"icon48.png"
]
如果希望images文件夹下的所有png图片都可被显示,可以通过如下声明实现:
"web_accessible_resources": [
"images/*.png"
]
桌面提醒窗口提供了四种事件:ondisplay
、onerror
、onclose
和onclick
。
除了用户主动关闭桌面提醒窗口外,还可以通过cancel
方法自动关闭。下面的代码可以实现5秒后自动关闭窗口的效果。
setTimeout(function(){
notification.cancel();
},5000);
由于桌面提醒界面可能将不再支持引入JS脚本,桌面提醒窗口与其他界面的通信本节不进行讲解。
桌面提醒已经被纳入了W3C草案,相关信息可以访问http://dev.chromium.org/developers/design-documents/desktop-notifications/api-specification查看。
除此之外,也可以通过Chrome提供的chrome.notifications
方法来创建功能更加丰富的提醒框。