브라우저 히스토리(세션 기록) 정보를 반환하거나 제어합니다.
.length
: 등록된 히스토리 개수
.scrollRestoration
: 히스토리 탐색시 스크롤 위치 복원 여부 확인 및 지정
.state
: 현재 히스토리에 등록된 데이터(상태)
.back()
: 뒤로 가기
.forward()
: 앞으로 가기
.go(위치)
: 현재 페이지 기준 특정 히스토리 '위치' 로 이동
> 모든 브라우저 (safari 제외)는 제목 옵션을 무시합니다.
.pushState(상태, 제목, 주소)
: 히스토리에 상태(데이터) 및 주소를 추가
.replaceState(상태, 제목, 주소)
: 현재 히스토리의 상태 및 주소를 교체
<a id="#hello1">Hello 1</a>
<a id="#hello2">Hello 2</a>
<a id="#hello3">Hello 3</a>
console.log(history)
history.go(2) //앞으로 2번 페이지 이동
history.go(-2) //뒤로 2번 페이지 이동
예시코드
<style>
body {
margin: 0;
}
nav {
background-color: white;
padding: 10px;
border: 4px solid;
position: fixed;
bottom: 0;
right: 0;
}
nav input {
width: 50px;
}
section {
height: 100vh;
border: 10px solid;
box-sizing: border-box;
}
section.page1 {
color: red;
}
section.page2 {
color: orange;
}
section.page3 {
color: green;
}
</style>
<body>
<nav>
<a href="#/page1">p1</a>
<a href="#/page2">p2</a>
<a href="#/page3">p3</a>
<input type="text" />
</nav>
<div id="app">
<section id="/page1" class="page1">
<h1>Page 1</h1>
</section>
<section id="/page2" class="page2">
<h1>Page 2</h1>
</section>
<section id="/page3" class="page3">
<h1>Page 3</h1>
</section>
</div>
</body>
const page1 = /* html */ `
<section class="page1">
<h1>Page1</h1>
</section>
`;
const page2 = /* html */ `
<section class="page2">
<h1>Page2</h1>
</section>
`;
const page3 = /* html */ `
<section class="page3">
<h1>Page3</h1>
</section>
`;
const pageNotFound = /* html */ `
<section>
<h1>404! page Not Found</h1>
</section>
`;
const pages = [
{ page: "#/page1", template: page1 },
{ page: "#/page2", template: page2 },
{ page: "#/page3", template: page3 },
];
const appEl = document.querySelector("#app");
const render = () => {
console.log(location);
const page = pages.find((page) => page.page === location.hash);
console.log(page);
appEl.innerHTML = page ? page.template : pageNotFound;
};
window.addEventListener("popstate", () => render());
render();
const pagePush = (num) => {
history.pushState(`전달할 데이터-${num}`, "", `#/page${num}`);
render();
};
const inputEl = document.querySelector("nav input");
inputEl.addEventListener("keydown", (event) => {
pagePush(event.target.value);
});