자바스크립트의 History 객체는 사용자가 방문한 URL 목록을 담고 있는 객체로, 이를 활용하면 브라우저의 방문 기록에서 앞으로 또는 뒤로 이동하거나, 목록에 있는 특정 URL을 불러올 수 있습니다.
History 객체는 window.history 형태로 접근할 수 있으며, 대표적인 메서드와 속성은 다음과 같습니다.
- history.length: 현재 세션에서 방문한 페이지 수를 반환합니다.
- history.back(): 직전 페이지로 이동합니다.
- history.forward(): 다음 페이지로 이동합니다.
- history.go(n): 지정한 숫자만큼 히스토리를 이동합니다(음수는 뒤로, 양수는 앞으로).
예제 코드
다음은 자바스크립트에서 History 객체를 구현하는 예제 코드입니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.sample {
font-size: 18px;
font-weight: 500;
}
</style>
</head>
<body>
<h1>JavaScript History object</h1>
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to check our history length
</h3>
<script>
let sampleEle = document.querySelector(".sample");
document.querySelector(".Btn").addEventListener("click", () => {
sampleEle.innerHTML = "Your history length is = " + history.length;
});
</script>
</body>
</html>실행 결과
위 코드를 실행하면 아래와 같은 화면이 나타납니다.

'CLICK HERE' 버튼을 클릭하면 현재 세션의 히스토리 길이가 화면에 출력됩니다.

정리
History 객체는 SPA(싱글 페이지 애플리케이션)나 페이지 간 탐색 흐름을 제어할 때 매우 유용하게 활용됩니다. history.length 속성을 통해 사용자가 세션 내에서 몇 개의 페이지를 거쳐 왔는지 확인할 수 있으며, back(), forward(), go() 메서드를 조합하면 브라우저의 뒤로 가기·앞으로 가기 동작을 프로그래밍 방식으로 제어할 수 있습니다.