Notification HTML5新屬性,復制代碼創建HTML文件,瀏覽器查看效果
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>桌面通知</title> 6 <script src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script> 7 </head> 8 <body> 9 <button onclick="show_notification('新消息', '開局一把槍一條狗,裝備全靠撿!')">顯示通知</button> 10 11 <script> 12 function show_notification(title, msg) { 13 var Notification = window.Notification || window.mozNotification || window.webkitNotification; 14 var data = { 15 body: msg, // 消息內容 16 icon: 'https://gss0.bdstatic.com/6LZ1dD3d1sgCo2Kml5_Y_D3/sys/portrait/item/a2f3c8cbb2bbc4dcccabd7d4cbbdb0a1c23e' // 消息圖標 17 }; 18 19 if(Notification){ // 檢測是否支持桌面通知 20 if(Notification.permission == "granted") { // 已經允許通知 21 var instance = new Notification(title, data); 22 instance.onclick = function() { // 點擊事件 23 alert('你點擊了消息彈框!'); 24 console.log('onclick'); 25 instance.close(); 26 }; 27 instance.onerror = function() { // 錯誤 28 console.log('onerror'); 29 }; 30 instance.onshow = function() { // 打開事件 31 console.log('onshow'); 32 }; 33 instance.onclose = function() { // 關閉事件 34 console.log('onclose'); 35 }; 36 }else{ // 第一次詢問或已經禁止通知(如果用戶之前已經禁止顯示通知,那么瀏覽器不會再次詢問用戶的意見,Notification.requestPermission()方法無效) 37 Notification.requestPermission(function(status) { 38 if(status === "granted"){ // 用戶允許 39 var instance = new Notification(title, data); 40 instance.onclick = function() {}; 41 instance.onerror = function() {}; 42 instance.onshow = function() {}; 43 instance.onclose = function() {}; 44 }else{ // 用戶禁止 45 return false 46 } 47 }); 48 } 49 }else{ 50 alert('瀏覽器不支持桌面通知!'); 51 } 52 53 } 54 55 </script> 56 </body> 57 </html>