본문 바로가기
WEB/JAVASCRIPT

자바스크립트로 페이지 이동(location.href, location.replace())

by 둥바 2022. 6. 30.

우리는 이전까지, html태그인 <a href="#"></a> 를 통해서 페이지를 이동해왔다.

자바스크립트의 Window 객체의 프로퍼티인, location을 통해서도 웹 문서의 주소를 다룰 수 있다.

가장 많이 사용되는 것은 location.href와 location.replace()인데, 다음과 같은 차이가 있다.

 

location.href location.replace()
location 객체의 프로퍼티 location 객체의 메소드
웹브라우저의 히스토리가 기억됨 웹브라우저의 히스토리 기억 안됨
뒤로가기 가능 뒤로가기(호출한 페이지로 이동) 불가

 

location.replace()의 경우에는 뒤로가기가 불가능하기 때문에, 보안상 뒤로가기를 해서는 안되는 경우에 사용하기 적합하다.

 

예제로 확인해보자.

 

<!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>Document</title>
    <script>
       function juso(){
        location.replace("http://google.com");
        //replace() 함수 사용, 뒤로가기 이전 페이지 주소 기록 없음
        //location.href="http://google.com"; 
        //href라는 프로퍼티 사용, 뒤로가기 할 때는 이전 페이지 주소 기록 O
       }

    </script>
</head>
<body>
    <h1>내부 자바스크립트 호출기법</h1>
    <h2>하이퍼링크로 이동할 경우</h2>>
    <h3>1) replace()함수적용이 안된다.(뒤로가기 기능)</h3>
    <a href="#" onclick="juso()">이동</a><br>
    <h2>버튼으로 이동할 경우</h2>
    <h3>2)replace()함수적용이 된다.(뒤로가기 불가능)</h3>
    <button onclick="juso()">이동</button>
    <hr>
    <h1>인라인 자바스크립트 기법</h1>
    <button onclick="location.href='http://google.com'">현재페이지에서</button>
    <button onclick="location.replace('http://google.com')">현재페이지에서(뒤로가기안됨)</button>
    <button onclick="window.open('http://google.com')">새창에서</button>
    <button onclick="window.open('http://google.com','구글','width=430,height=500,location=no,scrollbars=yes')">팝업창으로</button>
    <button onclick="parent.location.href='http://google.com'">상위프레임에서</button>
</body>
</html>