谷歌浏览器显示通知消息JS代码
点击显示通知会弹出通知对话框,如下图效果:
h5通知消息对话框代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>开心洋葱谷歌浏览器通知消息JS代码</title> <script type="text/javascript" src="//cdn.bootcss.com/jquery/3.2.0/jquery.js"></script> <style> * {margin: 0; padding: 0;} body, html {width: 100%; height: 100%;} </style> </head> <body> 点击下面的《显示通知》按钮,谷歌浏览器会自动弹出是否当前域名允许通知消息对话框,点击允许,即可弹出通知对话框。 <button id="tip1" class="tip1">显示通知</button> <script> $(function() { var timer = null, title = $('title').text(); $('#tip1').on('click', function() { showMsgNotification('这是标题-》来自开心洋葱', '这里是消息内容,来源自开心洋葱网站,百度搜索《开心洋葱》,网址http://75271.com'); return false; }); $('body').on('click', function() { clearInterval(timer); $('title').text(title); }); function showMsgNotification(title, msg) { var Notification = window.Notification || window.mozNotification || window.webkitNotification; if(Notification) {//支持桌面通知 if(Notification.permission == "granted") {//已经允许通知 var instance = new Notification(title, { body: msg, icon: "http://images.75271.com/Public/Uploads/logo.png", }); instance.onclick = function() { $('body').css({'background': 'red'}); console.log('onclick'); instance.close(); }; instance.onerror = function() { console.log('onerror'); }; instance.onshow = function() { console.log('onshow'); }; instance.onclose = function() { console.log('onclose'); }; }else {//第一次询问或已经禁止通知(如果用户之前已经禁止显示通知,那么浏览器不会再次询问用户的意见,Notification.requestPermission()方法无效) Notification.requestPermission(function(status) { if (status === "granted") {//用户允许 var instance = new Notification(title, { body: msg, icon: "images/reload.png" }); instance.onclick = function() { // Something to do }; instance.onerror = function() { // Something to do }; instance.onshow = function() { // Something to do }; instance.onclose = function() { // Something to do }; }else {//用户禁止 return false } }); } }else {//不支持(IE等) var index = 0; clearInterval(timer); timer = setInterval(function() { if(index%2) { $('title').text('【 】'+ title);//这里是中文全角空格,其他不行 }else { $('title').text('【新消息】'+ title); } index++; if(index > 20) { clearInterval(timer); } }, 500); } } }); </script> </body> </html>