上周在公司做的一个Web聊天程序,需要一个即时消息提醒并且带有声音提示的功能,在网上找了一下资料,Jquery有个一插件 Jquery.Notify 这个运用比较
广,官网有他的详细介绍(https://notifyjs.com/)我这边只是依据我的需求简单的运用了一下;对了!他还有相应的Bootstrap封装的版本,功能似乎更加强大
(http://bootstrap-notify.remabledesigns.com/),不多说了,先贴一下我的代码,有问题的地方还请提出:
$(function(){
var receiveIcon;
var receiveMessage;
var audioElementHovertree;
var showNotification =false;
//只在当前页面失去焦点时提示消息
window.onblur = function () {
showNotification = true;
}
window.onfocus = function () {
showNotification = false;
}});
//消息提醒
function check() {
// Let's check if the browser supports notifications
if (!("Notification" in window)) {
//alert("This browser does not support desktop notification");
return false;
}
if (Notification.permission !== "granted") {
Notification.requestPermission(function (permission) {
// Whatever the user answers, we make sure we store the information
if (!('permission' in Notification)) {
Notification.permission = permission;
}
});
return false;
}
return showNotification;
}
function notifyMe() {
if (check()) {
var notification = new Notification('新的消息', {
icon: receiveIcon,
//body: "Hey there! You've been notified!",
body:receiveMessage
});
notification.onshow = function () {
$('audio').remove();
audioElementHovertree = document.createElement('audio');
audioElementHovertree.setAttribute('src', 'http://w.qq.com/audio/classic.mp3');
audioElementHovertree.setAttribute('autoplay', 'autoplay'); //打开自动播放
//audioElement.load();
}
notification.onclick = function () {
window.focus();
};
setTimeout(notification.close.bind(notification), 5000);//auto clear notifications
}
}