js 调用浏览器的提示Web Notifications

关于调用浏览器的提示:
Web Notifications是HTML5 的一个特性,目前我知道的有谷歌浏览器和windows edge对它进行了支持

function notice(data){
  data = data || {};
  if (window.Notification){

    //Notification类提供了一个requestPermission方法,用来请求用户授权,代码如下:
   //当这段代码执行时,浏览器会询问用户,是否允许该站点显示消息通知
   Notification.requestPermission(function(status) {
      //status是授权状态,如果用户允许显示桌面通知,则status为'granted'
      console.log('status: ' + status);
 
      //permission只读属性
      var permission = Notification.permission;
      //default 用户没有接收或拒绝授权请求 不能显示通知
      //granted 用户接受授权请求 允许显示通知
      //denied  用户拒绝授权请求 不允许显示通知
 
    console.log('permission: ' + permission);

    if(Notification.permission === 'granted'){
     var notification = new Notification(data.title||'', {
        body: data.content||''
        ,icon: data.avatar||'http://tp2.sinaimg.cn/5488749285/50/5719808192/1'
      });
    }else {
      Notification.requestPermission();
    };
  }


//onshow函数在消息框显示时会被调用
//可以做一些数据记录及定时操作等
notification.onshow = function() {
    console.log('notification shows up');
    //5秒后关闭消息框
    setTimeout(function() {
        n.close();
    }, 5000);
};
 
//消息框被点击时被调用
//可以打开相关的视图,同时关闭该消息框等操作
notification.onclick = function() {
    alert('open the associated view');
    //opening the view...
    n.close();
};
 
//当有错误发生时会onerror函数会被调用
//如果没有granted授权,创建Notification对象实例时,也会执行onerror函数
notification.onerror = function() {
    console.log('notification encounters an error');
};
 
//一个消息框关闭时onclose函数会被调用
notification.onclose = function() {
    console.log('notification is closed');
}
//调用
var data = {
  username:'马云',
  content:'我来了',
  avatar:'http://tp2.sinaimg.cn/5488749285/50/5719808192/1'
}
notice({
  title: '来自 '+ data.username +' 的消息'
  ,content: data.content
  ,avatar: data.avatar
});

猜你喜欢

转载自blog.csdn.net/caiyongshengCSDN/article/details/89235761
今日推荐