CSS&JS/👀Study and Copy
[JS]페이지 갱신 없이 주소 바꾸기(history.pushState(), history.replaceState()
arancia_
2023. 1. 4. 14:52
- webisfree : 자바스크립트 history 객체 페이지 갱신 없이 페이지 전환, pushstate
- MDN :
History.replaceState() - Web API | MDN
History.replaceState() 메서드는 현재 history를 수정해 메소드의 매개 변수에 전달 된 stateObj, title, URL로 대체합니다. 이 방법은 특히 일부 유저의 동작에 대한 응답으로 history 객체의 상태나 현재 history
developer.mozilla.org
이것만으론 리액트를 완전히 대체할 수 없겠지만... 늘 궁금했음 어차피 리액트도 자바스크립트로 만드는건데 대체 어떻게 페이지 갱신없이 주소창을 바꿀 수 있는걸까?????????? 자바스크립트의 무슨 기능을 쓴걸까? 했는데 pushState였다
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>history.pushState</title>
</head>
<body>
<a href="https://developer.mozilla.org/ko/docs/Web/API/History/pushState" target="_blank">history.pushState</a>
<a href="https://developer.mozilla.org/ko/docs/Web/API/History/replaceState" target="_blank">history.replaceState</a>
<h1>주소창을 잘 보셈</h1>
<button data-url="hello">버튼1</button>
<button data-url="world.html">버튼2</button>
<button data-url="test.html">버튼3</button>
<!-- 스크립트 -->
<script>
const $$btns = document.querySelectorAll('BUTTON');
function change_url(e){
const $btn = e.target;
const url = $btn?.dataset?.url;
history.pushState('','',url); //replaceState란것도 있음
}
for(const $btn of $$btns){
$btn.addEventListener('click',change_url);
}
</script>
</body>
</html>
|
cs |