วันพฤหัสบดีที่ 25 เมษายน พ.ศ. 2556

HTML5 :Notification API

วันนี้มีลูกเล่นที่น่าสนใจมานำเสนออีกแล้วครับ อ่านจากชื่อตอนแล้วใครนึกออกบ้างเอ่ย

พูดถึง Notification ทุกคนน่าจะนึกถึง facebook หรือ window live messenger ใช่ครับเราจะทำประมาณนั้น

Notication API หรือชื่อเต็มคือ Web Notification API เป็น API ที่ทำให้เราสามารถสร้าง notification ไว้เด้งขึ้นมาบนเดสก์ท็อปของผู้ใช้ได้นั่นเอง เหมือน window live messenger เลยเชียวหละ ซึ่งประโยชน์เช่นคอยแสดงราคาทองทุกครั้งเมื่อมีการเปลี่ยนแปลง ช่วงนี้ยิ่งฮ็อตๆ อยู่ครับ

วันนี้จะมาเสนอ Notification API ของ WebKit ครับ ซึ่งรันได้บน chrome นั่นเอง ซึ่งมี 2 อินเทอร์เฟซ สำหรับใช้งาน

1. NotificationCenter ซึ่งใช้ในการร้องขอ permission ในการใช้งาน Notification API , คงสถานะของการอนุญาตและสร้าง Notification ซึ่งมี method ให้ใช้งานดังนี้

 - Notification createNotification(in DOMString iconUrl, in DOMString title, in DOMString body) ใช้ในการสร้าง notification โดยระบุ icon , title และ body ครับ

 - Notification createHTMLNotification(in DOMString url) ใช้ในการสร้าง Notification แบบหน้า HTML ครับ คือโยน url ของหน้าที่ต้องการใช้เป็น notification ลงไปเลยนั่นเอง

 - Int checkPermission(); ใช้สำหรับเรียกดูระดับการใช้งานว่าอนุญาตรึเปล่า

 - void requestPermission([in Fuction callback]) ใช้สำหรับขอคำยินยอมในการใช้ Notification API ครับ

Demo
    window.webkitNotifications.createNotification(‘icon.png’,’My Title’,’My Notification’);

2. Notification คือตัว notification ที่เราสามารถนำมาแสดงได้เลยผ่านเมธอดตามด้านล่างครับ

 - show() ใช้สำหรับแสดง notification บนเดสก์ท็อปของผู้ใช้
 - cancel() ใช้ในการลบ notification ออกจากเดสก์ท็อปหรอคิว

ต่อไปเป็น event ที่เราสามารถเล่นได้ครับ

 - ondisplay : ตอนแสดงบนเดสก์ท็อป
 - onclose : ตอนปิด notification ทั้งจากคลิกปิดเอง และจาก cancel()
 - onerror : เมื่อเกิดข้อผิดพลาด

มาเล่นกันดีกว่าโค้ดอยู่ด้านล่างครับ รันใน chrome ได้เท่านั้นครับ

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Notification API</title>

    <script type="text/javascript">
        var notificationCount = 0;

        function setPermission(){

            if(webkitNotifications){
                window.webkitNotifications.requestPermission();
            }else{
                alert("Not Support Nofication API");
            }
        }

        function fireNotification(){
            notificationCount++;

            var notification = webkitNotifications.createNotification(null,'Number : '+notificationCount, 'This is Notification '+notificationCount);

            notification.show();
        }
    </script>
</head>
<body>
    <p>Click set permission to allow notifications, then fire a notification</p>
    <section>
        <button id="setPermission" onclick="setPermission();">Set Permission</button>
        <button id="fireNotification" onclick="fireNotification();">Fire Notification</button>
    </section>
</body>
</html>

ผลลัพธ์


ความรู้จาก HTML5 Developer's Cookbook ครับผม