IT/Script
jquery history 제어
상짱
2020. 2. 28. 18:00
반응형
- 뒤로가기
history.back();
OR
history.go(-1);
- 앞으로 가기
history.forward();
OR
history.go(1);
- history 이벤트 감지 ( pushState / popstate )
// state : 직렬화할 수 있는 모든 것의 값
// title : history title
// url : history url / 익스플로러 url 변경됨.
history.pushState( state , title , url );
- history API 예제 ( https://developer.mozilla.org/ko/docs/Web/API/History_API )
History API
DOM의 Window 객체는 history 객체를 통해 브라우저의 세션 기록에 접근할 수 있는 방법을 제공합니다. history는 사용자를 자신의 방문 기록 앞과 뒤로 보내고 기록 스택의 콘텐츠도 조작할 수 있는, 유용한 메서드와 속성을 가집니다.
developer.mozilla.org
window.onpopstate = function(event) {
alert(`location: ${document.location}, state: ${JSON.stringify(event.state)}`)
}
history.pushState({page: 1}, "title 1", "?page=1")
history.pushState({page: 2}, "title 2", "?page=2")
history.replaceState({page: 3}, "title 3", "?page=3")
history.back() // alerts "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back() // alerts "location: http://example.com/example.html, state: null"
history.go(2) // alerts "location: http://example.com/example.html?page=3, state: {"page":3}"
- Develop source
- pushState 할때, title 값에 따라 state 는 초기화가 되는 듯하다.
- state 의 직렬화되는 값은 현재의 정보가 아닌, 이전정보를 자동으로 가지고 온다.
- list 는 항상 push 로 동작하게 하고,
- popstate 할때, list 를 state 정보로 교체한다.
// 전역변수
let list = [];
// history 이벤트 감지
$(window).bind("popstate" , function(event) {
let state = event.originalEvent.state;
if( state.length == 0 ){
location.href = "/index.do";
}else{
list = state;
let target = state[ state.length - 1 ];
fnPageMoveXXXX( target.hUrl , target.hData ); // 사용자함수
}
});
// 화면이동 - 특정함수에 히스토리 push
list.push({ hUrl : "/test01.do" , hData : {} });
history.pushState( list , "contents", location.href );
반응형