浏览器通知Web Notifications实例页面

回到相关文章 »

代码:

HTML代码:
<button id="button">有人想加你为好友</button>
<p id="text"></p>
                
JS代码:
if (window.Notification) {
    var button = document.getElementById('button'), text = document.getElementById('text');
    
    var popNotice = function() {
        if (Notification.permission == "granted") {
            var notification = new Notification("Hi,帅哥:", {
                body: '可以加你为好友吗?',
                icon: '//image.zhangxinxu.com/image/study/s/s128/mm1.jpg'
            });
            
            notification.onclick = function() {
                text.innerHTML = '张小姐已于' + new Date().toTimeString().split(' ')[0] + '加你为好友!';
                notification.close();    
            };
        }    
    };
    
    button.onclick = function() {
        if (Notification.permission == "granted") {
            popNotice();
        } else if (Notification.permission != "denied") {
            Notification.requestPermission(function (permission) {
              popNotice();
            });
        }
    };
} else {
    alert('浏览器不支持Notification');    
}
                

效果: