2016年8月8日 星期一

[Chrome] Notification 通知視窗




window.addEventListener('load', function () {
            //確認使用者是否允許跳窗,如果沒有,就跳窗取權限
            if (window.Notification && Notification.permission !== "granted") {
                Notification.requestPermission(function (status) {
                    if (Notification.permission !== status) {
                        Notification.permission = status;
                    }
                });
                
            }
            function NotifyMsg() {
                var option = {
                    tag: 'Notification',
                    body: '測試測試測試',
                    data: 'I am a data',
                    icon: '' //可以自訂ICON
                }

                var n = new Notification("Title", option);
                setTimeout(n.close.bind(n), 5000);
                console.log(n.data);
               
                n.onclick = function (event) {
                    event.preventDefault(); // prevent the browser from focusing the Notification's tab
                    window.open('http://www.google.com.tw/', '_blank');
                }
            }

            var button = document.getElementsByTagName('button')[0];
            button.addEventListener('click', function () {
                // If the user agreed to get notified
                // Let's try to send ten notifications
                if (window.Notification && Notification.permission === "granted") {
                    NotifyMsg();                
                    }

                    // If the user hasn't told if he wants to be notified or not
                    // Note: because of Chrome, we are not sure the permission property
                    // is set, therefore it's unsafe to check for the "default" value.
                else if (window.Notification && Notification.permission !== "denied") {
                        Notification.requestPermission(function (status) {
                        if (status === "granted") {
                            NotifyMsg();
                        }
                         // Otherwise, we can fallback to a regular modal alert
                        else {
                            alert("Hi!");
                        }
                    });
                }
                    // If the user refuses to get notified
                else {
                    // We can fallback to a regular modal alert
                  alert("Hi!");
                }
            });
          
        });



參考資料: MDN


沒有留言:

張貼留言