HTML5桌面通知Notification



HTML5桌面通知Notification。桌面通知,我们经常看到的比如QQ在右下角的消息提醒。在网页中我们也可以用Javascript模拟实现这一功能,只是这个消息框是浏览器中进行控制的。目前浏览器依然是一个严格的沙盒工作模式,这种模式把浏览器和桌面的通信隔离开。Notification可以跨越沙盒通过桌面向用户发出浏览器的通知。现在Html5中可以实现这一功能。在手机端,也就Blackberry browser实现了(完全实现),实现这一功能的浏览器均以webkit为内核。应用的范围还很有限,在HTML5如火如荼的今天,我们依然可以做个很好的展望。

API介绍
  桌面提醒功能是由window对象下的webkitNotifications来实现的,通过window.webkitNotifications将返回一个NotificationCenter对象。这个对象没有属性,但是却关联着四个方法:
构建桌面通知的基本步骤
一、检测浏览器是否支持
通过window.webkitNotifications可以判断浏览器是否支持notification

 

if(!window.webkitNotifications){
alert(“您的浏览器不支持Notification桌面通知!”);
}
二、权限只有获得用户授权才可以显示Notification。
requestPermission()
  这个方法用于向用户请求获得消息提醒的权限,分别对应着3中状态:“granted”(状态值:0)表示用户同意消息提醒;“default”(状态值:1)表示默认状态,用户既未拒绝,也未同意;“denied”(状态值:1)表示用户拒绝消息提醒。只有在状态值为0的时候才能够允许消息提醒,这个值保存在一个内部变量中,并且是只读的,通过checkPermission()方法可以提取到这个状态值。

//请求授权,如果成功则执行回调函数
function RequestPermission (callback) {
window.webkitNotifications.requestPermission(callback);
}
function showNotification(){
if (window.webkitNotifications.checkPermission() > 0) {
RequestPermission(showNotification);
}else{
//show Notification here..
}

}

三、createNotification()

  这个方法以纯消息的方式创建提醒消息,它接受三个参数:iconURL, title, body。这三个参数均为字符串格式,iconURL表示一个图标地址、title表示消息标题、body表示消息主体,默认这三个参数为空字符串。
调用这个方法会返回一个Notification对象,我们可以针对这个对象做更多的设置
属性:
  dir:设置消息的排列方向,可取值为“auto”(自动), “ltr”(left to right), “rtl”(right to left)。
  tag:为消息添加标签。如果设置此属性,当有新消息提醒时,标签相同的消息,后一个消息框会替换先前一个,不会出现多重消息提示框。
  onshow:事件属性,当消息框显示的时候触发该事件;
  onclick:事件属性,当点击消息框的时候触发该事件;
  onclose:事件属性,当消息关闭的时候触发该事件;
  onerror:事件属性,当出现错误的时候触发该事件;(TODO:错误类型)
方法:
  addEventListener && removeEventListener:常规的添加和移除事件方法;
  show:显示消息提醒框;
  close:关闭消息提醒框;
  cancel:关闭消息提醒框(这个方法和close方法产生的效果是一样,不清楚他们之间有什么深层次的区别)
四、createHTMLNotification()
  这个方法以HTML方式创建消息提醒,它接受一个参数,即HTML消息文档的URL。同样调用这个方法也会返回一个Notification对象,这个对象与用纯文本方式创建消息提醒返回的Notification对象相同,故对其属性和方法就不重述了。
注意:桌面提醒功能要在服务器的环境下才能够正常使用

 

【下面内容为对api的运用】
1. 只弹出一个通知窗口
这个问题比较好解决,因为通知对象拥有一个名为”replaceId”的属性。指定该属性后,只要是相同replaceId的通知窗口弹出,都会覆盖之前弹出的窗口。在实际项目中是给所有的弹出窗口赋了一个相同的replaceId。不过需要注意的是,这种覆盖行为只在同域下有效。
2. 确保页面Focus时不弹出通知窗口
这个问题主要是在于判断浏览器窗口是否处于Focus状态,目前除了监听window的onfocus和onblur事件之外,貌似没有更好的方式。在项目中就是通过这种方式来记录窗口的Focus状态,然后当消息到达时根据Focus状态来判断是否弹出窗口。
$(window).bind( ‘blur’, this.windowBlur).bind( ‘focus’, this.windowFocus);
使用该方法需要注意的地方是,事件注册的事件点应该尽可能的靠前,如果注册太晚则当用户打开页面后再离开就会很容易出现状态的误判。
3. 识别多Tab的Focus状态
多页面间的状态共享可以通过本地存储来实现:
浏览器窗口Focus时修改本地存储中指定key的值为”focus”
浏览器窗口Blur时修改本地存储中指定key的值为”blur”
需要注意的是,Chrome下从一个Tab切换到另一个Tab时,Blur有可能比Focus后写入存储中,因此修改Focus状态时需要异步处理。
/*window on focus事件*/
//用延时是为了解决多个Tab之间切换时,始终让Focus覆盖其他Tab的Blur事件
//注: 如果在点击Tab之前没有Focus到document上则点击Tab是不会触发Focus的
setTimeout( function(){
    Storage.setItem( ‘kxchat_focus_win_state’, ‘focus’ );
}, 100);
/*window on blur事件*/
Storage.setItem( ‘kxchat_focus_win_state’, ‘blur’ );
实现以上状态共享后,新的消息到达后,只需要查看本地存储中’kxchat_focus_win_state’的值是否为blur,如果为blur才弹出窗口。
4. 通知窗口的事件响应
通知窗口支持onclick等事件响应,而响应函数中的作用范围属于创建该窗口的页面。如下代码:
var n = dn.createNotification(
    img,
    title,
    content
);
//确保只有一个提醒
n.replaceId = this.replaceId;
n.onclick = function(){
    //激活弹出该通知窗口的浏览器窗口
    window.focus();
    //打开IM窗口
    WM.openWinByID( data );
    //关闭通知窗口
    n.cancel();
};
在onclick的响应函数中访问的window对象即属于当前创建页面,因此可以很方便的与当前页面进行交互。以上代码便实现了点击弹出窗口会跳转到对应的浏览器窗口和打开IM窗口。
【最后是当前谷歌提供的api官方文档】
This is a DRAFT specification and subject to change.
Note that the latest version of the spec is here: http://dev.w3.org/2006/webapi/WebNotifications/publish/ but this page reflects what’s implemented in the latest version of Chromium.
The Notification interface
This interface represents a notification object.
interface Notification : EventTarget {
 // display methods
 void show();
 void cancel();
 // event handler attributes
 attribute Function ondisplay;
 attribute Function onerror;
 attribute Function onclose;
 attribute Function onclick;
}
Attributes
ondisplay
event listener function corresponding to event type “display”.  This listener must be called when the notification is displayed to the user, which need not be immediately when show() is called.
onerror
event listener function corresponding to event type “error”.  This listener must be called when the notification cannot be displayed to the user because of an error.
onclose
event listener function corresponding to event type “close”.  This listener must be called when the notification is closed by the user.  This event must not occur until the “display” event.
onclick
event listener function corresponding to event type “click”.  This listener must be called when the notification has been clicked on by the user.
Methods
show
Causes the notification to displayed to the user.  This may or may not happen immediately, depending on the constraints of the presentation method.
cancel
Causes the notification to not be displayed.  If the notification has been displayed already, it must be closed.  If it has not yet been displayed, it must be removed from the set of pending notifications.
The NotificationCenter interface
The NotificationCenter interface exposes the ability for web pages to create Notification objects.
interface NotificationCenter {
 // Notification factory methods.
 Notification createNotification(in DOMString iconUrl, in DOMString title, in DOMString body) throws(Exception);
 optional Notification createHTMLNotification(in DOMString url) throws(Exception);
 // Permission values
 const unsigned int PERMISSION_ALLOWED = 0;
 const unsigned int PERMISSION_NOT_ALLOWED = 1;
 const unsigned int PERMISSION_DENIED = 2;
 // Permission methods
 int checkPermission();
 void requestPermission(in Function callback);
}
The NotificationCenter interface is available via the Window interface through the webkitNotifications property.
interface Window {
 attribute NotificationCenter webkitNotifications;
}
Methods
createNotification
Creates a new notification object with the provided content.  iconUrl contains the URL of an image resource to be shown with the notification; title contains a string which is the primary text of the notification; body contains a string which is secondary text for the notification.  If the origin of the script which executes this method does not have permission level PERMISSION_ALLOWED, this method will throw a security exception.
createHTMLNotification
The parameter url contains the URL of a resource which contains HTML content to be shown as the content of the notification.  If the origin of the script which executes this method does not have permission level PERMISSION_ALLOWED, this method will throw a security exception.  In Chromium, only http:, https:, and chrome-extension: schemes are allowed for url.
checkPermission
Returns an integer, either PERMISSION_ALLOWED, PERMISSION_NOT_ALLOWED, or PERMISSION_DENIED, which indicates the permission level granted to the origin of the script currently executing.
PERMISSION_ALLOWED (0) indicates that the user has granted permission to scripts with this origin to show notifications.
PERMISSION_NOT_ALLOWED (1) indicates that the user has not taken an action regarding notifications for scripts from this origin.
PERMISSION_DENIED (2) indicates that the user has explicitly blocked scripts with this origin from showing notifications.
requestPermission
Requests that the user agent ask the user for permission to show notifications from scripts.  This method should only be called while handling a user gesture; in other circumstances it will have no effect. This method is asynchronous.  The function provided in callback will be invoked when the user has responded to the permission request.  If the current permission level is PERMISSION_DENIED, the user agent may take no action in response to requestPermission.
Lifetime of notifications
If the page which generates a notification was generated is closed, the notification itself will not be closed, but events will not be delivered, as the script execution context is no longer present.
链接地址:http://dev.chromium.org/developers/design-documents/desktop-notifications/api-specification