JavaScript로 현재 페이지 URL 가져오기
브라우저에서 현재 열려 있는 웹 페이지의 URL을 확인하려면 window.location.href 속성을 사용하면 됩니다. 이 속성은 현재 문서의 전체 URL을 문자열 형태로 반환합니다.
브라우저 개발자 도구(DevTools)의 콘솔(Console) 탭에 아래 코드를 입력한 후 Enter 키를 눌러 결과를 직접 확인해 보세요.
var currentURL = window.location.href;
console.log(currentURL);
window.location 객체란?
window.location 객체는 현재 문서의 위치 정보를 담고 있으며, href 외에도 다양한 속성을 제공합니다.
window.location.protocol— 프로토콜(예: https:)window.location.host— 호스트명과 포트 번호window.location.pathname— 도메인 이후의 경로window.location.search— 쿼리 문자열(?key=value)window.location.hash— 해시(#section)
이처럼 window.location 객체를 활용하면 URL 전체뿐 아니라 필요한 부분만 골라서 쉽게 다룰 수 있습니다.