JS

230105 JS history객체

주영재 2023. 1. 5. 19:22

history객체

 

  • history.go(-1)//기록이동. -1이면 뒤로, 1이면 앞으로, -3이면 3번 뒤로 -1을 통해 뒤로가기를 직접 지정할 수도 있다.
  • history.back();//뒤로가기
  • history.replaceState(저장할데이터, 바꿀제목, 바뀐주소); //새로운기록추가. 가령 뒤로가기에서 1,2,3번페이지가 있을 때 2번페이지라는 기록을 바꾸는 것
  • history.pushState();첫번째는 공백(null), 두번째는 문자열로 제목-얘도 공백(''), 주소//기록을 추가. 
  • history.state //페이지데이터

    저장할데이터-state객체. null일수도 있음
    바꿀제목 title-대부분의 브라우저는 이 파라미터를 무시하기에 공백으로 표현
    바뀐주소 url-주소

※공백도 데이터임

<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
    1번페이지
<button onclick="location.href='index06.html'">페이지이동</button>


<h3>리플레이스 스테이트</h3>
<button onclick="func()">기록변경하기</button>

<script>
    function func(){
        // history.pushState(null,'','변경.html');//브라우저 기록추가
        //원래 index5->index6인데, 중간에 변경이라는 기록을 추가하는 것


        history.replaceState('','',null);//브라우저의 기록을 변경
    }

    //기록을 변경해서 사용할 데이터를 ''으로 바꿔주면, 사용자가 뒤로가기 버튼을 누른것을 감지할 수 있음.
    //history.state속성으로 확인이 가능함
    if(history.state==''){
        alert('기록이 변경됨');
    }


</script>



</body>
</html>

<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
    
2번페이지
<button onclick="history.go(-1)">뒤로가기</button>

</body>
</html>

 

페이지 이동하면 index06으로, 뒤로가기 버튼을 누르면 index05로 이동

 

기록변경하기를 누르고 index06으로 이동한 뒤 뒤로가기를 누르면 알림창이 뜸

 

history.pushState()는 브라우저의 기록을 추가해 준다.

원래 index05->index06인데, 그 사이에 pushState구문에 넣었던 '주소'라는 기록을 추가해주는 것.

 

history.replaceState는 이와 달리 브라우저의 기록을 변경해주는 것.

만일 위 예시에서 replaceState의 주소에 어떤 특정한 주소를 지정해주면 index05가 아닌 다른 주소로 이동한다.

 

※replace를 조절하면 사용자가 뒤로가기 버튼을 누른 것을 감지할 수 있다!