상세 컨텐츠

본문 제목

세션 히스토리와 내비게이션

프로그래밍/스크립트

by 라제폰 2015. 10. 23. 10:11

본문

 – 차례 –  W3C 원본
    1. 5.4 세션 히스토리와 내비게이션
      1. 5.4.1 브라우징 문맥의 세션 히스토리
      2. 5.4.2 The History interface
      3. 5.4.3 The Location interface
        1. 5.4.3.1 보안
      4. 5.4.4 세션 히스토리 구현 노트
    2. 5.5 웹 브라우징
      1. 5.5.1 문서들간의 이동
      2. 5.5.2 HTML 파일의 페이지 로드 처리 모델
      3. 5.5.3 XML 파일의 페이지 로드 처리 모델
      4. 5.5.4 텍스트 파일의 페이지 로드 처리 모델
      5. 5.5.5 이미지의 페이지 로드 처리 모델
      6. 5.5.6 플러그인을 사용하는 컨텐츠의 페이지 로드 처리 모델
      7. 5.5.7 DOM 을 갖지 않는 인라인 컨텐츠의 페이지 로드 처리 모델
      8. 5.5.8 조각 식별자(#)로 이동
      9. 5.5.9 히스토리 이동
        1. 5.5.9.1 이벤트 정의
      10. 5.5.10 문서 언로드
        1. 5.5.10.1 이벤트 정의
      11. 5.5.11 문서 로드 취소

이 섹션에서 문맥이라 함은 브라우징 문맥browsing context를 말합니다.

5.4 세션 히스토리와 내비게이션

5.4.1 브라우징 문맥의 세션 히스토리

문맥에 포함된 Document 들의 연속을 세션 히스토리라고 말합니다.

The sequence of Documents in a browsing context is its session history.

History 객체는 문맥의 세션 히스토리에 들어 있는 페이지들을 나타냅니다. 각각의 문맥(중첩된 문맥을 포함)은 유일한 세션 히스토리를 갖습니다.

History objects provide a representation of the pages in the session history of browsing contexts. Each browsing context, including nested browsing contexts, has a distinct session history.

문맥의 세션 히스토리에 들어 있는 각각의 Document 객체는 History 객체의 유일한 인스턴스와 연결됩니다. 이러한 것들은 모두 동일한 세션 히스토리 모델을 따라야 합니다.

Each Document object in a browsing context's session history is associated with a unique instance of the History object, although they all must model the same underlying session history.

브라우저 제작자 대상 내용입니다.

History 객체는 자신의 문맥의 세션 히스토리를, 세션 히스토리 항목의 평면화된 목록으로 나타냅니다. 각각의 세션 히스토리 항목은 URL, 혹은 상태 객체, 또는 둘 모두로 구성됩니다.

History objects represent their browsing context's session history as a flat list of session history entries. Each session history entry consists of either a URL or a state object, or both, and may in addition have a title, a Document object, form data, a scroll position, and other information associated with it.

브라우저 제작자 대상 내용입니다.

세션 히스토리 항목들과 연관된 타이틀 들은 Document의 현재 타이틀과는 어떠한 관계를 가질 필요도 없습니다. 세션 히스토리 항목의 타이틀은, 사용자가 문서의 히스토리를 탐색할 수 있도록 할 목적으로, 그 시점에서의 문서의 상태를 표시할 목적을 가진 것입니다.

Titles associated with session history entries need not have any relation with the current title of the Document. The title of a session history entry is intended to explain the state of the document at that point, so that the user can navigate the document's history.

상태 객체와 연관되어있지 않은 URL은 사용자(또는 스크립트)가 페이지에서 페이지로 이동할 때 세션 히스토리에 더해집니다.

URLs without associated state objects are added to the session history as the user (or script) navigates from page to page.

상태 객체란 사용자 인터페이스의 상태를 나타내는 객체입니다.

state object is an object representing a user interface state.

페이지들은 상태 객체를 세션 히스토리에서의 자신을 나타내는 항목과, "다음" 항목 사이에 추가할 수 있습니다. 그러면 사용자(또는 스크립트)가 히스토리 상에서 뒤로 갈 때 이러한 것이 스크립트로 반환되며, 따라서 저자들은 비록 1 페이지 짜리 어플리케이션에서도 "내비게이션" 개념을 사용할 수 있습니다.

Pages can add state objects between their entry in the session history and the next ("forward") entry. These are then returned to the script when the user (or script) goes back in the history, thus enabling authors to use the "navigation" metaphor even in one-page applications.

상태 객체는 두가지 주된 목적을 갖도록 의도되었습니다. 첫번째는, URL에 미리 파싱된 상태의 설명을 저장함으로서 간단한 경우에는 저자가 직접 파싱할 필요가 없게끔 하는 것입니다.(사용자에 의해 전달된 URL들을 다루기 위해서는 여전히 파싱이 필요하기 때문에 이것은 미미한 최적화에 불과합니다). 두번째는, 보통은 URL에 저장하지 않는 상태 정보를 저자들이 저장할 수 있게끔 하기 위함인데, 이것이 현재의 Document 인스턴스에만 적용되며 새로운 Document가 열리면 재생성되어야 하기 때문입니다.

State objects are intended to be used for two main purposes: first, storing a preparsed description of the state in the URL so that in the simple case an author doesn't have to do the parsing (though one would still need the parsing for handling URLs passed around by users, so it's only a minor optimization), and second, so that the author can store state that one wouldn't store in the URL because it only applies to the current Document instance and it would have to be reconstructed if a new Document were opened.

후자의 간단한 예를 들어보자면, 움직이도록 만들어진 팝업 div의 정밀한 위치를 추적하는 것 같은 것인데, 이렇게 하면 사용자가 뒤로가기를 했을 경우 그러한 애니메이션을 동일한 위치에서 시작할 수 있을 것입니다. 또는, (이렇게 하지 않았다면) URL에 들어 있는 정보를 바탕으로 서버에서부터 가져와야 했을 데이터들의 캐쉬에 포인터를 하나 삽입함으로서, 앞으로 가거나 뒤로가기를 했을 때 정보를 다시 받아올 필요가 없습니다.

An example of the latter would be something like keeping track of the precise coordinate from which a popup div was made to animate, so that if the user goes back, it can be made to animate to the same location. Or alternatively, it could be used to keep a pointer into a cache of data that would be fetched from the server based on the information in the URL, so that when going back and forward, the information doesn't have to be fetched again.


어떠한 시점에서든, 세션 히스토리의 항목들 중 하나는 현재 항목입니다. 이것은 문맥의 현재 문서를 나타내는 항목입니다. 현재 항목은 종종 Document의 위치에 관한 항목입니다. 물론, 그 문서에 의해 히스토리에 더하여진 상태 객체 항목들 중 하나일수도 있습니다.

At any point, one of the entries in the session history is the current entry. This is the entry representing the active document of the browsing context. The current entry is usually an entry for the location of the Document. However, it can also be one of the entries for state objects added to the history by that document.

보관된 사용자 상태의 항목은 사용자 에이전트에서 정의하는 상태입니다. 이 명세서에서는 어떠한 상태들을 보관할지 명시하지 않습니다.

An entry with persisted user state is one that also has user-agent defined state. This specification does not specify what kind of state can be stored.

예를 들어, 일부 사용자 에이전트는 스크롤 위치를 기억해두거나, 폼 컨트롤의 값을 보관해두려고 할 수 있습니다.

For example, some user agents might want to persist the scroll position, or the values of form controls.

상태 객체를 구성하는 항목들은 자신이 더해지는 시점에서의 활성 문서로서 동일한 Document를 공유합니다.

Entries that consist of state objects share the same Document as the entry for the page that was active when they were added.

조각 식별자(#)에서만 차이가 있는 연속적인 항목들 역시 동일한 Document를 공유합니다.

Contiguous entries that differ just by fragment identifier also share the same Document.

동일한 Document를 공유하는 모든 항목들(그리고, 하나의 특정 문서에서 단순히 상태만 다를 뿐인 것들)은 정의에 의해 연속적입니다.

All entries that share the same Document (and that are therefore merely different states of one particular document) are contiguous by definition.

브라우저 제작자 대상 내용입니다.

5.4.2 The History interface

interface History {
  readonly attribute long length;
  void go(in optional long delta);
  void back();
  void forward();
  void pushState(in any data, in DOMString title, in optional DOMString url);
  void replaceState(in any data, in DOMString title, in optional DOMString url);
};
window . history . length

병합 세션 히스토리의 항목들의 숫자를 반환합니다.

Returns the number of entries in the joint session history.

window . history . go( [ delta ] )

병합 세션 히스토리에서 주어진 숫자만큼의 단계를 앞으로 가거나 뒤로 갑니다.

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

0을 넘기면 현재 페이지를 리로드합니다.

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(datatitle [, url ] )

주어진 타이틀로, 주어진 데이터를 세션 히스토리에 씁니다. URL이 주어졌다면 함께 적용합니다.

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

window . history . replaceState(datatitle [, url ] )

주어진 타이틀과 데이터로 세션 히스토리의 현재 항목을 갱신합니다. URL이 주어졌다면 함께 적용합니다.

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

병합 세션 히스토리란 최상위 문맥과 History 객체를 공유하는 모든 완전히 활성인 Document 객체의 모든 문맥의 세션 히스토리들을 병합한 객체입니다. 병합 세션 히스토리의 현재 항목만을 제외하고, 각각의 세션 히스토리의 현재 항목은 제거됩니다.

The joint session history of a History object is the union of all the session histories of all browsing contexts of all the fully active Documentobjects that share the History object's top-level browsing context, with all the entries that are current entries in their respective session historiesremoved except for the current entry of the joint session history.

병합 세션 히스토리의 현재 항목이란 그 세션 히스토리에서 가장 마지막에 설정된 현재 항목입니다.

The current entry of the joint session history is the entry that most recently became a current entry in its session history.

병합 세션 히스토리의 항목들은 각각의 개별적인 세션 히스토리에 추가된 시간 순으로 정렬됩니다. (이러한 모든 문맥들은 정의에 의해 이벤트 루프를 공유하므로, 각각의 세션 히스토리에 항목이 추가된 것에는 잘 정의된 순서가 항상 존재합니다) 각각의 항목은 인덱스를 갖습니다; 최초의 항목은 0이며, 이후 항목들은 연속적으로 증가하는 정수(1, 2, 3,...)을 갖습니다.

Entries in the joint session history are ordered chronologically by the time they were added to their respective session histories. (Since all thesebrowsing contexts by definition share an event loop, there is always a well-defined sequential order in which their session histories had their entries added.) Each entry has an index; the earliest entry has index 0, and the subsequent entries are numbered with consecutively increasing integers (1, 2, 3, etc).

브라우저 제작자 대상 내용입니다.

게임을 하나 가정해 봅니다. 사용자는 하나의 줄을 따라서 이동할 수 있는데, 사용자가 있는 위치는 항상 어떤 좌표를 가지며, 또한 사용자는 특정 좌표와 대응하는 페이지를 북마크하여 이후에 돌아올 수 있습니다.

Consider a game where the user can navigate along a line, such that the user is always at some coordinate, and such that the user can bookmark the page corresponding to a particular coordinate, to return to it later.

그러한 게임에서 x=5 라는 위치를 구현한 정적인 페이지는 다음과 같을 것입니다:

A static page implementing the x=5 position in such a game could look like the following:

  1. <!DOCTYPE HTML>
  2. <!-- this is http://example.com/line?x=5 -->
  3. <title>Line Game - 5</title>
  4. <p>You are at coordinate 5 on the line.</p>
  5. <p>
  6. <a href="?x=6">Advance to 6</a> or
  7. <a href="?x=4">retreat to 4</a>?
  8. </p>

이러한 시스템에서의 문제는, 사용자가 클릭할때마다 페이지 전체가 리로드된다는 것입니다. 이러한 것을 스크립트를 통해 다른 방법으로 해 봅니다:

The problem with such a system is that each time the user clicks, the whole page has to be reloaded. Here instead is another way of doing it, using script:

  1. <!DOCTYPE HTML>
  2. <!-- this starts off as http://example.com/line?x=5 -->
  3. <title>Line Game - 5</title>
  4. <p>You are at coordinate <span id="coord">5</span> on the line.</p>
  5. <p>
  6. <a href="?x=6" onclick="go(1); return false;">Advance to 6</a> or
  7. <a href="?x=4" onclick="go(-1); return false;">retreat to 4</a>?
  8. </p>
  9. <script>
  10. var currentPage = 5; // prefilled by server
  11. function go(d) {
  12. setupPage(currentPage + d);
  13. history.pushState(currentPage, document.title, '?x=' + currentPage);
  14. }
  15. onpopstate = function(event) {
  16. setupPage(event.state);
  17. }
  18. function setupPage(page) {
  19. currentPage = page;
  20. document.title = 'Line Game - ' + currentPage;
  21. document.getElementById('coord').textContent = currentPage;
  22. document.links[0].href = '?x=' + (currentPage+1);
  23. document.links[0].textContent = 'Advance to ' + (currentPage+1);
  24. document.links[1].href = '?x=' + (currentPage-1);
  25. document.links[1].textContent = 'retreat to ' + (currentPage-1);
  26. }
  27. </script>

스크립트가 지원되지 않는 시스템에서도 앞서의 예와 마찬가지로 동작합니다. 물론, 스크립트가 지원되는 사용자들은 훨씬 빠르게 이동할 수 있는데, 네트워크를 경유하지 않고도 같은 일을 하기 때문입니다. 이에 더해, 고지식한 스크립트 기반의 접근방법에서 사용자가 가졌을 사용자 경험과는 대조적으로, 북마크와 세션 히스토리 탐색 역시 작동합니다.

In systems without script, this still works like the previous example. However, users that do have script support can now navigate much faster, since there is no network access for the same experience. Furthermore, contrary to the experience the user would have with just a naïve script-based approach, bookmarking and navigating the session history still work.

위의 예제에서 pushState() 메서드에 전달된 매개변수 data는 서버로 보내어졌을 것과 같은 정보이지만, 좀 더 편리한 형태로 되어 있으므로, 사용자가 움직일때마다 스크립트에서 URL을 파싱할 필요가 없습니다.

In the example above, the data argument to the pushState() method is the same information as would be sent to the server, but in a more convenient form, so that the script doesn't have to parse the URL each time the user navigates.

어플리케이션에서 세션 히스토리 항목으로 보내는 타이틀이 그 시점에서의 문서의 타이틀이 아닐 수도 있습니다. 예를 들어, title 요소에 블럭을 보여주는 간단한 페이지가 있습니다. 단순히 이전의 상태로 돌아가는 경우에는 시간을 필요로 하지 않을 것이 명백하므로, 세션 히스토리 타이틀에 시간을 넣는 것은 적절하지 않을 것입니다.

Applications might not use the same title for a session history entry as the value of the document's title element at that time. For example, here is a simple page that shows a block in the title element. Clearly, when navigating backwards to a previous state the user does not go back in time, and therefore it would be inappropriate to put the time in the session history title.

  1. <!DOCTYPE HTML>
  2. <TITLE>Line</TITLE>
  3. <SCRIPT>
  4. setInterval(function () { document.title = 'Line - ' + new Date(); }, 1000);
  5. var i = 1;
  6. function inc() {
  7. set(i+1);
  8. history.pushState(i, 'Line - ' + i);
  9. }
  10. function set(newI) {
  11. i = newI;
  12. document.forms.F.I.value = newI;
  13. }
  14. </SCRIPT>
  15. <BODY ONPOPSTATE="recover(event.state)">
  16. <FORM NAME=F>
  17. State: <OUTPUT NAME=I>1</OUTPUT> <INPUT VALUE="Increment" TYPE=BUTTON ONCLICK="inc()">
  18. </FORM>

5.4.3 The Location interface

문맥의 세션 히스토리에 들어있는 각각의 Document 객체들은 Location 객체의 유일한 인스턴스와 연결됩니다.

Each Document object in a browsing context's session history is associated with a unique instance of a Location object.

document . location [ = value ]
window . location [ = value ]

현재 페이지의 위치와 함께 Location 객체를 반환합니다.

Returns a Location object with the current page's location.

값을 설정하여 다른 페이지로 이동할 수 있습니다.

Can be set, to navigate to another page.

브라우저 제작자 대상 내용입니다.

Location 객체는 문서의 현재 주소를 나타내며, history 객체에 항목을 초가하거나 변경해서 문맥의 세션 히스토리의 현재 항목을 변경하는 것을 허용합니다.

Location objects provide a representation of their document's current address, and allow the current entry of the browsing context's session history to be changed, by adding or replacing entries in the history object.

interface Location {
  stringifier attribute DOMString href;
  void assign(in DOMString url);
  void replace(in DOMString url);
  void reload();
 
  // URL decomposition IDL attributes  
           attribute DOMString protocol;
           attribute DOMString host;
           attribute DOMString hostname;
           attribute DOMString port;
           attribute DOMString pathname;
           attribute DOMString search;
           attribute DOMString hash;
 
  // resolving relative URLs
  DOMString resolveURL(in DOMString url);
};
location . href [ = value ]

현재 페이지의 위치를 반환합니다.

Returns the current page's location.

값을 설정하여 다른 페이지로 이동할 수 있습니다.

Can be set, to navigate to another page.

location . assign(url)

주어진 페이지로 이동합니다.

Navigates to the given page.

location . replace(url)

세션 히스토리에서 현재의 페이지를 제거한 후 주어진 페이지로 이동합니다.

Removes the current page from the session history and navigates to the given page.

location . reload()

현재 페이지를 다시 로드합니다.

Reloads the current page.

url = location . resolveURL(url)

주어진 상대 URL을 절대 URL로 해석합니다.

Resolves the given relative URL to an absolute URL.

브라우저 제작자 대상 내용입니다.

Location 인터페이스는 또한 다음의 IDL 속성들의 URL 분해를 보충합니다: protocol, host, port, hostname, pathname, search, hash.

The Location interface also has the complement of URL decomposition IDL attributesprotocolhostporthostnamepathnamesearch, and hash.These must follow the rules given for URL decomposition IDL attributes, with the input being the current address of the associated Documentobject, as an absolute URL (same as the href attribute), and the common setter action being the same as setting the href attribute to the new output value.

브라우저 제작자 대상 내용입니다.브라우저 제작자 대상 내용입니다.브라우저 제작자 대상 내용입니다.

5.5 웹 브라우징

브라우저 제작자 대상 내용입니다.

5.5.9 히스토리 이동

브라우저 제작자 대상 내용입니다.

세션 히스토리 항목으로 이동할 때 popstate 이벤트가 발생하는 경우가 있습니다.

The popstate event is fired in certain cases when navigating to a session history entry.

interface PopStateEvent : Event {
  readonly attribute any state;
  void initPopStateEvent(in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in any stateArg);
};
event . state

pushState() 또는 replaceState() 메서드에 전달된 정보의 사본을 반환합니다.

Returns a copy of the information that was provided to pushState() or replaceState().

브라우저 제작자 대상 내용입니다.


이전의 URL에서 단지 해시(#)만 다른 세션 히스토리 항목으로 이동할 때 hashchange 이벤트가 발생합니다.

The hashchange event is fired when navigating to a session history entry whose URL differs from that of the previous one only in the fragment identifier.

interface HashChangeEvent : Event {
  readonly attribute DOMString oldURL;
  readonly attribute DOMString newURL;
  void initHashChangeEvent(in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in DOMString oldURLArg, in DOMString newURLArg);
};
event . oldURL

이전의 세션 히스토리 항목의 URL을 반환합니다.

Returns the URL of the session history entry that was previously current.

event . newURL

현재 세션 히스토리 항목의 URL을 반환합니다.

Returns the URL of the session history entry that is now current.

브라우저 제작자 대상 내용입니다.


세션 히스토리 항목으로 이동할때 pageshow 이벤트가 발생합니다.

The pageshow event is fired when traversing to a session history entry.

세션 히스토리 항목에서 이동할때 pagehide 이벤트가 발생합니다.

The pagehide event is fired when traversing from a session history entry.

interface PageTransitionEvent : Event {
  readonly attribute boolean persisted;
  void initPageTransitionEvent(in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in boolean persistedArg);
};
event . persisted

페이지가 새롭게 로드되는 중인 경우 false를 반환합니다 (load 이벤트도 발생합니다). 그렇지 않은 경우 true를 반환합니다.

Returns false if the page is newly being loaded (and the load event will fire). Otherwise, returns true.

브라우저 제작자 대상 내용입니다.

5.5.10 문서 언로드

브라우저 제작자 대상 내용입니다.

interface BeforeUnloadEvent : Event {
           attribute DOMString returnValue;
};
event . returnValue [ = value ]

이벤트의 반환값(사용자에게 보여줄 메시지)을 반환합니다.

Returns the current return value of the event (the message to show the user).

값을 설정하여 메시지를 업데이트할 수 있습니다.

Can be set, to update the message.

BeforeUnloadEvent에 특화된 초기화 메서드는 없습니다.

There are no BeforeUnloadEvent-specific initialization methods.

브라우저 제작자 대상 내용입니다.브라우저 제작자 대상 내용입니다.

관련글 더보기