添加新评论

Chrome Notifications

博客分类: 

web QQ,比价插件等都可以在浏览器里弹出一个消息框。其实实现起来还挺简单,主要用到window.webkitNotifications。

进入主题,

第一步需要检查浏览器是否开启了显示消息的权限。

// check permission

window.webkitNotifications.checkPermission();

如果没有权限,请求权限:

// request permission if 

window.webkitNotifications.requestPermission(function(){

  /*if (callback) {  

    callback(this.checkPermission());  

  }*/

});  

接着就能创建消息啦,通过show方法显示:

// create notification.

var notify = {icon: "", title: "Notify in Chrome", text: "This is come from \"Chrome's notification\""}

var notification = window.webkitNotifications.createNotification(notify.icon, notify.title, notify.text);

notification.show();

// bind events on notification.

notification.onclick = function(){};

notification.onclose = function(){};

notification.ondisplay = function(){};

notification.onerror = function(){};

notification.onshow = function(){};

 

Note:

在我本地实践时一直出不来消息,但是checkPermission这里又是有权限的。

 于是我去看了下通知设置的地方,步骤如下:

设置->显示高级设置->隐私设置 内容设置,然后找到通知一项,有如下选项,我本地默认是第二项选中:

 - 允许所有网站显示桌面通知
 - 网站尝试显示桌面通知时询问我(推荐)
 - 不允许任何网站显示桌面通知

修改成第一项就可以正常使用了。至于为什么第二项不行,我还没找到原因。

如下是英文的版本设置:
Settings->Show advanced settings->Privacy section, Content settings.

Notifications section:

 - Allow all sites to show desktop notifications: Select this option to let all sites automatically show you notifications.

 - Ask me when a site wants to show desktop notifications: Select this option if you want Google Chrome to alert you whenever a site wants to show you notifications. 

 - Do not allow any site to show desktop notifications:  Select this option to automatically deny sites from showing you notifications.

 

参考Links:

http://www.html5rocks.com/en/tutorials/notifications/quick/#disqus_thread

https://support.google.com/chrome/answer/3220216?hl=en

Total votes: 9437