Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript에서 현재 URL을 가져오는 방법 – window.location 활용법

JavaScript에서 현재 페이지의 URL을 확인하고 싶다면 window.location 객체를 사용하면 됩니다. 이 객체는 브라우저가 현재 로드한 문서의 위치(주소) 정보를 담고 있어, 별도의 라이브러리 없이 순수 JavaScript만으로 URL에 접근할 수 있습니다.

window.location.href란?

window.location.href는 현재 페이지의 전체 URL(href)을 문자열로 반환하는 속성입니다. 프로토콜(http/https), 도메인, 경로, 쿼리 스트링까지 포함된 전체 주소가 필요할 때 가장 많이 사용됩니다.

예를 들어 MVC 프로젝트나 일반 웹 애플리케이션에서 현재 접속 중인 페이지 주소를 알아내야 할 때 아래와 같이 활용할 수 있습니다.

예제 코드

<html>
    <body>
        <div>
            <p id="dd"></p>
        </div>
        <script type="text/javascript">
            var iid = document.getElementById("dd");
            alert(window.location.href);
            iid.innerHTML = "URL is " + window.location.href;
        </script>
    </body>
</html>

코드 설명

위 예제는 다음과 같이 동작합니다.

1. alert(window.location.href) — 페이지가 로드되는 즉시 현재 URL을 알림 창으로 표시합니다.
2. iid.innerHTML = "URL is " + window.location.href — id가 'dd'인 <p> 요소 안에 현재 URL 텍스트를 삽입하여 화면에 출력합니다.

window.location의 유용한 하위 속성들

전체 URL뿐 아니라 특정 부분만 추출해야 할 때도 window.location 객체가 유용합니다.

- window.location.protocol : 프로토콜 (예: https:)
- window.location.host : 호스트명과 포트 (예: www.example.com:8080)
- window.location.hostname : 도메인명만 (예: www.example.com)
- window.location.pathname : 경로 부분 (예: /products/list)
- window.location.search : 쿼리 스트링 (예: ?id=123)
- window.location.hash : 해시(#) 이후 부분 (예: #section1)

이처럼 window.location 객체 하나만 잘 활용하면 현재 URL과 관련된 거의 모든 정보를 손쉽게 다룰 수 있습니다.