Html5中的桌面通知Notification的实现

2019-01-28 21:12:29王冬梅

2> onshow 通知消息展示之后触发的事件
3> onerror 遇到错误会触发的事件
4> onclose close事件的处理

2. Notification对象会有什么属性/方法呢?利用控制台中的window对象输出点开查看就可以看到:

值得注意的是: requestPermission()方法仅在Notification对象有效,实例对象无效!!!这个方法是用来向用户申请显示通知的权限,只能被用户主动去调用(在页面onload中可以调用,可以向用户申请,之后再去发送...)

实例对象拥有的方法有:

    (1). close() 用于关闭通知消息 --> 也可以在onshow方法加延迟调用,提高用户体验感...

    (2). addEventListener() 监听事件(这个通用方法)

    (3). removeEventListener 卸载监听事件(通用,同上)

    (4). dispatchEvent 分派事件(同上)

接下来,写一个js测试, 如果使用的是谷歌浏览器,建议在设置中显示通知将本地服务地址加入允许通知

但是,http的域名在谷歌浏览器被默认关闭,还不允许更改,查看谷歌浏览器控制台有警告信息--->

index.js:78 [Deprecation] The Notification API may no longer be used from insecure origins. You should consider switching your application to a secure origin, such as HTTPS. See https://goo.gl/rStTGz for more details.

嗯,好吧,让加https证书,真的是有毒...虽然在自己的主页中添加该功能也只能在火狐浏览器爽一爽....

(腾讯云有免费一年的ssl证书,可自己进行安装...)

// index.js window.onload = function(){   let gxlself = new Gxlself()   gxlself.requestPermission()   setTimeout(()=>{     gxlself.showNotification()   },3000) } class Gxlself{    constructor(){     this.isNotificationSupported = "Notification" in window;    } isPermissionGranted(){ return Notification.permission === 'granted'; } requestPermission(){ if(!this.isNotificationSupported){ return; } Notification.requestPermission(status=>{ let permission = Notification.permission; }) } showNotification(){ if (!this.isNotificationSupported) { return; } if (!this.isPermissionGranted()) { return; } var n = new Notification("gxlself对您发来问候", { icon : 'gxlself.png', body : '欢迎来访,鄙人万分感激! 点击即可跳转至我的博客页面~' }); n.onshow = function () { console.log('gxlself已经发送通知信息'); setTimeout(function() { n.close(); }, 5000); } n.onclick = function () { location.href = 'http://gxlself.com/blog' n.close() } n.onerror = function (err) { console.log(err) } n.onclose = function () { console.log('gxlself消息窗口关闭') } } }