工作中遇到的问题:需要在页面写一个定时器 不停地去访问后台查看是否有新的预定订单 如果有的话要弹出在页面 而且这个弹窗要是全局的就是说不管现在管理员在浏览哪个网站的网页 他都可以看见这个弹框
其实这个原理很简单:首先会去判断一下当前浏览器是否支持桌面通知 如果支持 然后再去判断是否有权限弹窗
这个权限就是当前浏览器的设置了 比如chrome
你就可以继续下一步弹窗了 如果不支持的话 回去请求一下用户是否允许弹窗
function notifyMe(url) { // Let's check if the browser supports notifications if (!("Notification" in window)) { alert("This browser does not support desktop notification"); } // Let's check if the user is okay to get some notification else if (Notification.permission === "granted") { // If it's okay let's create a notification // var notification = new Notification("Hi there!"); var notification = new Notification('Title', { body : url, //icon : './images/test1.png' }); /*setTimeout(function() { notification.close(); }, 3600000);*/ } // Otherwise, we need to ask the user for permission // Note, Chrome does not implement the permission static property // So we have to check for NOT 'denied' instead of 'default' else if (Notification.permission !== 'denied') { Notification.requestPermission(function (permission) { // Whatever the user answers, we make sure we store the information if(!('permission' in Notification)) { Notification.permission = permission; } // If the user is okay, let's create a notification if (permission === "granted") { var notification = new Notification('Title', { body : url, }); } }); } // At last, if the user already denied any notification, and you // want to be respectful there is no need to bother him any more. }
创建通知对象的时候可以选择的部分属性:
通知对象所涉及到的事件:
另外定时器是我在开源中国社区中找的JHeartbeat
修改过后的jquery_heartbeat.js
/* * jHeartbeat 0.3.0 * download:http://www.jb51.net * (C)Alex Richards - http://www.ajtrichards.co.uk/ */ $.jheartbeat = { options: { url: "heartbeat_default.asp", delay: 10000, div_id: "test_div" }, beatfunction: function(){ }, timeoutobj: { id: -1 }, set: function(options, onbeatfunction) { if (this.timeoutobj.id > -1) { clearTimeout(this.timeoutobj); } if (options) { $.extend(this.options, options); } if (onbeatfunction) { this.beatfunction = onbeatfunction; } // Add the HeartBeatDIV to the page var result = document.getElementById(this.options.div_id); if(result == null){ $("body").append("<input type='hidden' id=\"" + this.options.div_id + "\" >"); } this.timeoutobj.id = setTimeout("$.jheartbeat.beat();", this.options.delay); }, beat: function() { $.ajax({ url: this.options.url, dataType: "json", type: "GET", /*error: function(e) { $('#'+ $.jheartbeat.options.div_id).append("Error Requesting Data"); },*/ success: function(data){ $('#'+ $.jheartbeat.options.div_id).val(data.url); } }); this.timeoutobj.id = setTimeout("$.jheartbeat.beat();", this.options.delay); this.beatfunction(); } };
JHeartbeat使用方法:
$(function () { console.log("dsfasdf"); $.jheartbeat.set({ url:"/test.do", delay:"10000", div_id:"test_div" },function () { var url = $('#'+ $.jheartbeat.options.div_id).val(); if(url != "" && url != "null"){ notifyMe(url); } }) });