HTML5 Notification 맛보기

ITWeb/개발일반 2011. 12. 14. 16:53
[원문]
http://www.html5rocks.com/en/tutorials/notifications/quick/

[번역문]
http://html5korea.co.kr/1993

[Notification Test용 Content Twitter API]
- http://twitter.com/statuses/user_timeline/계정명.json?count=목록수&callback=콜백함수(실행시킬함수명)
- 트위터 API 관련 : https://dev.twitter.com/

[참고사이트]
http://www.chromium.org/developers/design-documents/desktop-notifications/api-specification
http://dev.w3.org/2006/webapi/WebNotifications/publish/Notifications.html


[Notification Interface]

the Notification interface

interface Notification : EventTarget {

  void               show();
  void               cancel();
           attribute Function   onclick;
           attribute Function   onshow;
           attribute Function   onerror;
           attribute Function   onclose;
  void               setReplaceId(in DOMString replaceId);
           attribute DOMString  dir;
};


[Constructor]

Constructing a notification

  Notification Notification(in DOMString iconUrl, in DOMString title, in DOMString body);


[Code Example]

<!DOCTYPE html>

<html>

<head>

<title>HTML5 Notification</title>

<script type="text/javascript">

/*

[Notification Interface]

the Notification interface


interface Notification : EventTarget {


  void               show();

  void               cancel();

           attribute Function   onclick;

           attribute Function   onshow;

           attribute Function   onerror;

           attribute Function   onclose;

  void               setReplaceId(in DOMString replaceId);

           attribute DOMString  dir;

};


[Constructor]

Constructing a notification


  Notification Notification(in DOMString iconUrl, in DOMString title, in DOMString body);



*/


var noti;


/*

json

opt

resource

이미지 나 Content 가능

title

text 등록 가능 하며, HTML 코드 사용 안됨

content

text 등록 가능 하며, HTML 코드 사용 안됨

ondisplay

ondisplay function 등록

onclose

ondisplay function 등록
        .. 추가적인 이벤트 등록을 하고 싶다면 등록해서 사용하면 됩니다.

ex) {opt:'default', resource:'http://.....', title:'제목', content:'내용'}

*/

function createInstanceOfNotification(json) {

if ( window.webkitNotifications.checkPermission() == 0 ) {

switch ( json.opt ) {

case 'default' :

noti = window.webkitNotifications.createNotification(json.resource, json.title, json.content);

break;

case 'html' :

noti = window.webkitNotifications.createHTMLNotification(json.resource);

break;

}

noti.ondisplay = json.ondisplay;

noti.onclose = json.onclose;

noti.show();

} else {

window.webkitNotifications.requestPermission();

}

}


function eventNotificationOnDisplay () {

console.log('ondisplay catch');

for ( var i in arguments ) {

console.log ( i + ' : ' + arguments[i]);

}

}


function eventNotificationOnClose () {

console.log('onclose catch');

}

</script>

</head>

<body style='margin:0px; padding:0px;' topmargin='0px'  leftmargin='0px' marginheight='0px' marginwidth='0px'>

<button onclick='createInstanceOfNotification({opt:"default",resource:"banner1.png",title:"제목을 보여주세요.",content:"내용을 보여주세요.",ondisplay:eventNotificationOnDisplay,onclose:eventNotificationOnClose});'>window.webkitNotifications.createNotification - JSON</button><br>

<button onclick='createInstanceOfNotification({opt:"html",resource:"http://m.naver.com",ondisplay:eventNotificationOnDisplay,onclose:eventNotificationOnClose});'>window.webkitNotifications.createHTMLNotification - JSON</button><br>

</body>

</html>


※ 위 예제 코드에서 사용되는 console 는 크롬 브라우저에서 제공하는 Global Object 입니다. F12 를 눌러서 디버깅시 효과적으로 활용 하시면 매우 좋습니다.
- 관련 동영상 링크 입니다.
http://www.youtube.com/results?search_query=chrome+debug

이제 JSONP 를 이용한 예제 코드를 하나 더 작성해 볼 예정입니다.
JSONP 는 검색해 보시면 많은 내용들이 나옵니다.
그래도 쉽게 이해 할수 있는 article 링크 하나 걸어 봅니다.
http://www.ibm.com/developerworks/kr/library/wa-aj-jsonp1/

JSONP 의 기초개념은 
JSON String + CallBack 함수의 결합만 이해 하면 될 것 같습니다.
Request API 하나에 callback 함수를 지정해서 이걸 <script> 태그에 삽입하여 body 에서 callback 함수를 실행 하도록 하면 끝....



[JSONP 예제]

function jsonReceiver(json) {

    var size = json.length;


    for ( var i=0; i<size; i++ ) {

        console.log(json[i].source + ', ' + json[i].text + ', ' + json[i].user.screen_name);

        createInstanceOfNotification({opt:"default",resource:"",title:"",content:json[i].text});

    }

}


function createScript() {

    var scripts = document.createElement('script');


    scripts.src = 'http://twitter.com/statuses/user_timeline/sophistlv.json?count=4&callback=jsonReceiver';


    document.body.appendChild(scripts);

}
============================================================================================== 

<button onclick='createScript();'>Create Scripts JSONP</button>

※ 추가된 코드 입니다.

역시 모든 구현 예제 코드의 기본은 상단의 원문과 참고사이트의 코드를 기반으로 한 것입니다.
이를 가지고 응용하는 방법은 Biz 요구사항에 맞춰서 구현을 하시면 좋겠죠.. 
- Chrome 에서 테스트 된 것이구요.
- 관련 코드는 html 파일로 해서 서버에 올려 놓고 테스트 한 내용입니다.
- local file 형태로 실행 시키기면 동작 하지 않습니다.
- 동작하지 않는다는건 notification 의 show() 함수 실행 시 dialog 가 뜨지 않는다는 의미 입니다.
: