'html5'에 해당되는 글 8건

  1. 2016.07.13 [HTML] window.history 스펙
  2. 2012.03.16 HTML5 Server Sent Events 맛보기.
  3. 2012.03.15 HTML5 Server Sent Events 를 이용한 웹채팅 Prototype.
  4. 2011.12.14 HTML5 Notification 맛보기
  5. 2011.11.29 HTML5 Open 레퍼런스 공유.
  6. 2011.10.25 window.postMessage 알아보기.
  7. 2011.10.24 모바일 웹 : navigator.geolocation 이용하기.
  8. 2010.02.02 Quirks mode

[HTML] window.history 스펙

ITWeb/개발일반 2016. 7. 13. 17:50

window.history 스펙이라기 보다 그냥 history interface 내용을 가져온 것입니다.


원문)

https://html.spec.whatwg.org/multipage/browsers.html#the-history-interface


내용)

enum ScrollRestoration { "auto", "manual" };

interface History {
  readonly attribute unsigned long length;
  attribute ScrollRestoration scrollRestoration;
  readonly attribute any state;
  void go(optional long delta = 0);
  void back();
  void forward();
  void pushState(any data, DOMString title, optional USVString? url = null);
  void replaceState(any data, DOMString title, optional USVString? url = null);
};


본 내용을 찾아본 이유는 location.href 값을 변경하고 싶었고 변경 시 reloading 되지 않도록 하기 위해서 입니다.

pushState, replaceState 를 이용하면 원하는 기능을 구현 할 수 있습니다.


설명)

window . history . length

Returns the number of entries in the joint session history.

window . history . scrollRestoration [ = value ]

Returns the scroll restoration mode of the current entry in the session history.

Can be set, to change the scroll restoration mode of the current entry in the session history.

window . history . state

Returns the current state object.

window . history . go( [ delta ] )

Goes back or forward the specified number of steps in the joint session history.

A zero delta will reload the current page.

If the delta is out of range, does nothing.

window . history . back()

Goes back one step in the joint session history.

If there is no previous page, does nothing.

window . history . forward()

Goes forward one step in the joint session history.

If there is no next page, does nothing.

window . history . pushState(data, title [, url ] )

Pushes the given data onto the session history, with the given title, and, if provided and not null, the given URL.

window . history . replaceState(data, title [, url ] )

Updates the current entry in the session history to have the given data, title, and, if provided and not null, URL.


:

HTML5 Server Sent Events 맛보기.

ITWeb/개발일반 2012. 3. 16. 12:27
항상 그렇지만.. 저는 기본 문서 부터 봅니다..

[참고사이트]


[EventSource Interface]

[Constructor(DOMString url, optional EventSourceInit eventSourceInitDict)]
interface EventSource : EventTarget {
  readonly attribute DOMString url;
  readonly attribute boolean withCredentials;

  // ready state
  const unsigned short CONNECTING = 0;
  const unsigned short OPEN = 1;
  const unsigned short CLOSED = 2;
  readonly attribute unsigned short readyState;

  // networking
  [TreatNonCallableAsNull] attribute Function? onopen;
  [TreatNonCallableAsNull] attribute Function? onmessage;
  [TreatNonCallableAsNull] attribute Function? onerror;
  void close();
};

dictionary EventSourceInit {
  boolean withCredentials = false;
};



[Event Stream]
- 중요하다고 싶은 것만... 

Streams must be decoded as UTF-8

If the line is empty (a blank line)

Dispatch the event, as defined below.

If the line starts with a U+003A COLON character (:)

Ignore the line.

If the line contains a U+003A COLON character (:)

Collect the characters on the line before the first U+003A COLON character (:), and let field be that string.

Collect the characters on the line after the first U+003A COLON character (:), and let value be that string. If value starts with a U+0020 SPACE character, remove it from value.

Process the field using the steps described below, using field as the field name and value as the field value.

Otherwise, the string is not empty but does not contain a U+003A COLON character (:)

Process the field using the steps described below, using the whole line as the field name, and the empty string as the field value.

Once the end of the file is reached, any pending data must be discarded. (If the file ends in the middle of an event, before the final empty line, the incomplete event is not dispatched.)


The steps to process the field given a field name and a field value depend on the field name, as given in the following list. Field names must be compared literally, with no case folding performed.

If the field name is "event"

Set the event name buffer to field value.

If the field name is "data"

Append the field value to the data buffer, then append a single U+000A LINE FEED (LF) character to the data buffer.

If the field name is "id"

Set the last event ID buffer to the field value.

If the field name is "retry"

If the field value consists of only characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then interpret the field value as an integer in base ten, and set the event stream's reconnection time to that integer. Otherwise, ignore the field.

Otherwise

The field is ignored.



[Event Stream onmessage Event - data]

[Case 1]

data: 1

data: 2


data: 3


[Case 1's onmessage]

- onmessage 이벤트는 두번처리 됩니다.

- data: 1, data: 2 를 묶어서 하나의 이벤트로 그리고 data: 3 을 또 다른 이벤트로 처리 합니다.

- 결국,  empty line 이 없이 바로 연결된 경우는 data buffer 에 메시지가 함께 들어가게 되는 구조 입니다.

- 다른 버퍼에 담아서 이벤트를 분리 하고 싶다면 개행을 두번 해주시면 됩니다.  


[Case 2]

data: 1

data: 2 

 
[Case 2's onmessage]

이미 위에서 설명한 것 처럼 두번의 onmessage 이벤트가 발생 합니다. 



[Event Stream onmessage Event - event] 
- 별도 이벤트를 등록하기 위한 방법입니다.

[event stream 구조]
- wakeup 이라는 이벤트가 발생하도록 메시지를 전달 합니다.

event: wakeup

data: 12345678


[event 추가]
- DOM Event 처리랑 동일 합니다.
- 전달 받은 data buffer 의 12345678 은 event.data 에 전달 되고 onwakeup 이벤트가 발생하게 됩니다.

var eventSource = new EventSource('http://192.168.1.2/sse.html');


eventSource.addEventListener('wakeup', onwakeup, false);


function onwakeup (event) {

console.log("onwakeup");

console.log(event.data);

} 



[Event Stream onmessage Event - id]

이 넘은 불행하게도 아직 고려중인 듯 합니다. 



[text/event-stream]


※ 추가적으로 CORS 관련 문제는 이전에 작성한 PostMessage API 를 참고 하시면 좋을 것 같습니다.

:

HTML5 Server Sent Events 를 이용한 웹채팅 Prototype.

ITWeb/개발일반 2012. 3. 15. 17:04
고민 하다가 걍.. 부재중 메시지나 아니면.. 읽기 전에 메시지를 연속으로 보냈을때 오류를 방지 하기 위해서.. 아래 처럼 코드 살짝 수정했습니다. ^^;

[status.html]

<?php

header('Content-type: text/event-stream');

header('Content-Transfer-Encoding: UTF-8');

header('Connection: keep-alive');


$file = $_GET['f'];


echo file_get_contents($file);

file_put_contents($file, '', LOCK_EX);

flush();

?>



[messages.html]

<?php

$sender = $_GET['sender'];

$receiver = $_GET['receiver'];

$message = $_GET['message'];


$sendMessage = "\n\n" . 'id: ' . time() . "\n\n" . 'data: {sender:"' . $sender . '", receiver:"' . $receiver . '", message:"' . $message . '}' . "\n\n";


file_put_contents($receiver . '.txt', $sendMessage, FILE_APPEND|LOCK_EX);

?>




정말이지 완전 쌩초보 프로토타입이니 걍.. 참고만 하시길 바라며.. 
전혀 웹서버에 대한 과도한 traffic 에 대해서 고려되지 않은 내용임을 밝힙니다... ㅋㅋ
(SSE 도 결국은 http request 방식을 사용하기 때문에 traffic 부하가 있습니다.)

해야 할건 무지 많습니다.
기본 chatting message 에 대한 structure 도 만들어야 하고 traffic 에 대한 분산을 어떻게 할지도 고민해서 만들어야 하고...등등.. 
걍.. 맛보기이니.. 나머지는 각자 알아서 만들어 보세요.. ^^;;


[참고문서]


[실행화면]



[구조소개]

[chat.html]
- 대화 상대를 선택하게 되면 열리는 채팅창입니다.

[status.html]
- EventSource 에서 이벤트를 받을 서버 URL 입니다.

[messages.html]
- XHR 을 이용해서 메시지를 전송할 서버 URL 입니다.
- 이넘이 입력한 메시지를 받아서 기록하게 됩니다. 



[소스코드 - chat1.html]


[소스코드 - chat2.html]
- 아래 코드만 chat1.html 과 다릅니다.

var messageVO = {

sender:'jjeong',

receiver:'henry',

message:''

}


var eventSource = new EventSource('http://localhost/status.html?f=jjeong.txt');



[소스코드 - status.html]

<?php

header('Content-type: text/event-stream');

header('Content-Transfer-Encoding: UTF-8');

header('Connection: keep-alive');


$file = $_GET['f'];
 

echo file_get_contents($file);

flush();

?>



[소스코드 - messages.html]

<?php

$sender = $_GET['sender'];

$receiver = $_GET['receiver'];

$message = $_GET['message'];


$sendMessage = "\n\n" . 'id: ' . time() . "\n\n" . 'data: {sender:"' . $sender . '", receiver:"' . $receiver . '", message:"' . $message . '}' . "\n\n";


file_put_contents($receiver . '.txt', $sendMessage, LOCK_EX);

?>

 
:

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 가 뜨지 않는다는 의미 입니다.
:

HTML5 Open 레퍼런스 공유.

ITWeb/스크랩 2011. 11. 29. 13:26
공유라기 보다는 그냥 북마크가 맞는 표현 같내요.

[HTML5 Open Reference]
http://html5ref.clearboth.org/

[HTML5 Open Reference eBook]
http://www.clearboth.org/html5ref_ebook/
https://docs.google.com/viewer?a=v&pid=explorer&chrome=true&srcid=0BwKGpbna5w4_ZTIyYWViYzctOTJiMC00MzE4LWEyNmQtMmM5NGI3OGI3ZGE4&hl=en_US

늘 느끼는 거지만, 인터넷을 통해 이렇게 유용한 정보와 지식이 공유 된다는게 너무 좋습니다.
이런 공간을 통해서 저도 뭔가 도움을 줄 수 있다면 참 좋겠내요.. 


※ 더불어 이전에 북마킹 했던 글도 참고하세요.
http://jjeong.tistory.com/487

재능기부!!
:

window.postMessage 알아보기.

ITWeb/개발일반 2011. 10. 25. 10:01
[참고 URL]
https://developer.mozilla.org/en/DOM/window.postMessage
http://www.whatwg.org/specs/web-apps/current-work/multipage/web-messaging.html#web-messaging


window.postMessage 는 cross domain 간 데이터를 주고 받는데 아주 유용한 기법을 제공 합니다.
자세한 spec 은.. 위 URL 참고 하시면 됩니다.


http://192.168.1.1/siteA.html

0. siteB 를 allow 할 allowOrigin 정의를 합니다.
var allowOrigin = "http://192.168.2.1";

1. siteB 에서 전송한 postMessage 이벤트를 catch 하기 위해서 event 등록을 합니다.
window.addEventListener("message", postMessageController, true); 또는
window.attachEvent("onmesage", postMessageController);

2. siteB 의 postMessage 이벤트를 catch 해서 실행 시킬 postMessageController 함수 작성을 합니다.
function postMessageController(e) {
    if ( e.origin === allowOrigin ) {
        // 실행 시킬 코드를 작성 하세요.
        alert(e.data); // e.data 는 siteB 에서 전달 받은 message 입니다.
    }
}

http://192.168.2.1/siteB.html

0. siteA 와 통신 하기 위한 allowOrigin 을 정의 합니다. (allowOrigin 은 그냥 임의 정의한 변수명 입니다. 바꾸셔도 되요.)
var allowOrigin = "http://192.168.1.1"; 

1. siteA 로 전달할 message 용 함수를 작성 합니다.
function sendMessage () {
    window.parent.postMessage("Hi! Good to see you.", allowOrigin);
}
이 함수를 실행 시키면 siteA 의 postMessageController 가 동작 하게 됩니다. 



이 두개 파일의 구조는 siteA.html 에 iframe 으로 siteB.html 을 embedded 시켜놓은 구조 입니다.

<html>

<head>

<title>siteA.html</title>

</head>

<body style="background:#000000;">

<iframe name="siteB" id="siteB" src="http://192.168.2.1/siteB.html" border="0" frameborder="0" width="320" height="48" scrolling="no"></iframe>

</body>

</html>



위의 샘플 pseudo code 는 siteB 에서 siteA 로 메시지를 전달 하는 예 입니다.
그렇기 때문에 siteA 에서 siteB 로 메시지를 전달하고 싶을 경우는 siteB 에 event 등록해 주시고 siteA 에서 iframe 의 window 객체를 얻어서 postMessage 를 실행 시키시면 됩니다.


 
:

모바일 웹 : navigator.geolocation 이용하기.

ITWeb/개발일반 2011. 10. 24. 10:22
참고 URL : http://dev.w3.org/geo/api/spec-source.html
지원 브라우저는 safari, firefox, chrome 에서 지원됨.

<html>

<head>

<script>

function successCallback(position) {

alert(position.coords.latitude + " : " + position.coords.longitude);

}


function errorCallback(error) {

alert(error.message);

}


function load(){ 

if ( navigator.geolocation ) {

navigator.geolocation.getCurrentPosition(successCallback, errorCallback);

} else {

alert("geolocation not supported");

}

}

</script>

</head>

<body onload="load()">

</body>

</html>



크롬에서 로컬 파일 실행 시켜서 테스트 했더니 주소창에 "위치추적이 차단 되었습니다." 라고 아이콘 뜨고 안됩니다.
서버에 올려서 테스트 하시면 "허용/차단" 버튼 나오면서 정상 동작 확인 가능 합니다.

successCallback, errorCallback 함수 등에 대해서는 
기본 위의 참고URL 가셔서 spec 문서 한번 읽어 보시면 쉽게 이해 되실 거예요.

:

Quirks mode

ITWeb/개발일반 2010. 2. 2. 12:18


HTML5 관련 문서 읽다가
HTML 5 defines three modes: quirks mode, limited quirks mode and no quirks mode, of which only the latter is considered conforming to use. The reason for this is due to backwards compatibility. The important thing to understand is that there are some differences in the way documents are visually rendered in each of the modes; and to ensure the most standards compliant rendering, it is important to ensure no-quirks mode is used.
이 부분에서 quirk 내용이 있길래 remind 차원에서 다시 한번 찾아 봤습니다.
원문 : http://dev.w3.org/html5/html-author/#doctype-declaration





Quirks mode는 오래된 웹 브라우저들을 위해 디자인된 웹 페이지의 하위 호환성을 유지하기 위해 W3C나 IETF의 표준을 엄격히 준수하는 Standards Mode를 대신하여 사용되는 웹 브라우저의 기술을 나타낸다. 같은 코드라도 웹 브라우저마다 서로 해석을 달리 하기 때문에, 전혀 다른 결과물을 보여주게 된다.
원문 : http://ko.wikipedia.org/wiki/Quirks_mode

중요한 부분만 골라 보면.. 아래 두개 정도..
The reason for this is due to backwards compatibility.
it is important to ensure no-quirks mode is used.
: