標(biāo)題: Html5新特性Notification實(shí)現(xiàn)桌面消息推送 [打印本頁]

作者: heicc    時(shí)間: 2016-6-13 14:11
標(biāo)題: Html5新特性Notification實(shí)現(xiàn)桌面消息推送
     序:最近工作使用WorkTile,發(fā)現(xiàn)使用Chrome瀏覽器的時(shí)候如果有任務(wù)下發(fā)給我則會(huì)在桌面右下角提示(當(dāng)前瀏覽器為最小化模式)。感覺這個(gè)東西蠻有意思的,感覺可以給用戶更好的體驗(yàn),于是乎就查詢了一下,發(fā)現(xiàn)是Html5的新特性。

    0x01:IE內(nèi)核的瀏覽器還不可以,但在Chrome與Firefox上已經(jīng)實(shí)現(xiàn)了此API。

    0x02:代碼簡(jiǎn)單直接看吧
         notification.html
        
        
<!DOCTYPE html>
        <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <title>Html5 桌面消息推送</title>
        </head>
        <body>
            <input type="button" id="btn_Send" value="發(fā)送桌面消息" />
            <input type="button" id="btn_Close" value="關(guān)閉桌面消息" />
            <script src="http://c.51hei.com/a/a/g/66136371059279.jpg"></script>
            <script src="http://c.51hei.com/a/a/g/66136371028045.jpg"></script>
        </body>
        </html>

        notification.js
        
        var notif;  // 消息對(duì)象
        var i = 0;
        $(document).ready(function () {
            /* 注冊(cè)按鈕單擊事件 */
            $('#btn_Send').bind('click', function () {
                if (window.Notification) {  // 判斷瀏覽器是否支持Notification特性,Chrome與Firefox支持,IE內(nèi)核暫不支持
                    if (Notification.permission == 'granted') { // 判斷瀏覽器是否允許此站點(diǎn)發(fā)送桌面消息;granted為允許
                        notif = new Notification('Clown:', {
                            body: '呆子、在嗎?',
                            icon: 'http://taekwondoshow.com/Images/my_1.jpg',
                            tag: ++i    // ID,如果ID重復(fù)則前者會(huì)被覆蓋,如果ID不重復(fù)則一直疊加顯示。PS:Chrome最多同時(shí)顯示3條,F(xiàn)irefox則沒有限制。。。
                        });
        

                        notif.onclose = function () {   // 當(dāng)Notification被關(guān)閉時(shí)觸發(fā)
                            alert('消息被關(guān)閉了');
                        };
                        notif.onclick = function () {   // 當(dāng)Notification被單擊時(shí)觸發(fā)
                            alert('消息被單擊了');
                        }
                    } else {
                        Notification.requestPermission();
                    }
                } else {
                    alert('當(dāng)前瀏覽器不支持Notification特性!');
                }
            });
            $('#btn_Close').bind('click', function () {
                if (notif) {
                    notif.close();
                }
            });
        });

        










歡迎光臨 (http://www.torrancerestoration.com/bbs/) Powered by Discuz! X3.1