HTML DOM PopStateEvent 객체는 브라우저의 세션 히스토리(session history)가 변경될 때 발생하는 popstate 이벤트를 처리하는 이벤트 핸들러입니다. 사용자가 브라우저의 뒤로 가기·앞으로 가기 버튼을 누르거나, JavaScript에서 history.back(), history.forward(), history.go() 메서드가 실행되어 히스토리 탐색이 일어날 때 popstate 이벤트가 트리거됩니다.
참고로 history.pushState()나 history.replaceState() 메서드 호출 자체로는 popstate 이벤트가 발생하지 않습니다. 이 이벤트는 오직 히스토리 항목 간의 실제 탐색(navigation)이 일어날 때만 활성화된다는 점을 기억해 두면 좋습니다.
PopStateEvent의 주요 속성
| 속성 | 설명 |
|---|---|
| state | 현재 히스토리 항목에 저장된 상태(state) 객체의 복사본을 반환합니다. |
예제 코드
다음은 HTML DOM PopStateEvent 객체의 동작을 확인할 수 있는 예제입니다 −
<!DOCTYPE html>
<html>
<head>
<style>
html{
height:100%;
}
body{
text-align:center;
color:#fff;
background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) center/cover no-repeat;
height:100%;
}
p{
font-size:1.2rem;
}
.btn{
background:#0197F6;
border:none;
height:2rem;
border-radius:2px;
width:35%;
margin:2rem auto;
display:block;
color:#fff;
outline:none;
cursor:pointer;
}
</style>
</head>
<body>
<h1>DOM PopStateEvent Event Demo</h1>
<button onclick="display()" class="btn">Click Me</button>
<script>
function display(){
window.onpopstate = function(event) {
alert("location: " + document.location +
", state: " + JSON.stringify(event.state));
};
history.pushState({
page: 1
}, "title home", "?page=home");
history.pushState({
page: 2
}, "title about", "?page=about");
history.replaceState({
page: 3
}, "title contact", "?page=contact");
history.back();
history.back();
}
</script>
</body>
</html>
이 예제의 동작 흐름은 다음과 같습니다. 먼저 pushState() 메서드로 두 개의 히스토리 항목을 추가하고, replaceState()로 현재 항목을 교체한 뒤, back() 메서드를 두 번 호출해 히스토리를 거슬러 올라갑니다. 이 과정에서 popstate 이벤트가 발생하며, window.onpopstate 핸들러가 현재 문서의 위치(location)와 상태(state) 정보를 알림 창(alert)으로 출력합니다.
실행 결과
위 코드를 실행하면 다음과 같은 화면이 출력됩니다 −

"Click Me" 버튼을 클릭하면 PopStateEvent 객체의 동작 원리를 직접 확인할 수 있습니다 −

알림 창에서 "Ok" 버튼을 클릭하면 다음 히스토리 상태로 이동합니다 −
