예제 10-14: Location 객체 분석 보고서
본 문서는 현재 웹 문서의 URL 주소 정보를 조회하고, 새로운 페이지로 이동(네비게이션)하는 기능을 담당하는 `location` 객체의 개념과 주요 속성 및 메서드를 설명합니다.
1. Location 객체란 무엇인가요? (기초 개념)
`location` 객체는 현재 브라우저에 표시된 문서의 URL(Uniform Resource Locator) 정보를 담고 있는 자바스크립트의 내장 객체입니다. window.location의 형태로 사용되며, 접두사를 생략하고 간단히 location으로 호출할 수 있습니다.
💡 핵심 역할: 현재 페이지가 어떤 주소로 접속되어 있는지 파악(`href`, `hostname` 등)할 수 있을 뿐만 아니라, 값을 대입하거나
assign() 메서드를 호출하여 새로운 웹 페이지로 강제 이동시키는 리다이렉트 기능을 수행할 수 있습니다.
2. 제공된 HTML 원본 코드
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<meta charset="utf-8">
<title>예제 10-14 Location 객체</title>
</head>
<body>
<p>Location href: <b id="wh"></b>입니다.</p>
<p>Location hostname: <b id="awh"></b>입니다.</p>
<p>Location pathname: <b id="cd"></b>입니다.</p>
<p>Location protocol: <b id="pd"></b>입니다.</p>
<p>Location port: <b id="prt"></b>입니다.</p>
<h3>Location 객체</h3>
<button type="button" onclick="lct()">Location 정보 보기</button>
<button type="button" onclick="assgn()">새 문서 열기</button>
<script>
function lct() {
var hf = location.href;
var hn = location.hostname;
var pn = location.pathname;
var pt = location.protocol;
var prt = location.port;
document.getElementById("wh").textContent = hf;
document.getElementById("awh").textContent = hn;
document.getElementById("cd").textContent = pn;
document.getElementById("pd").textContent = pt;
document.getElementById("prt").textContent = prt;
}
function assgn(){
location.assign("https://w3schools.com/js/");
}
</script>
</body>
</html>
실시간 실행 화면
Location href: 입니다.
Location hostname: 입니다.
Location pathname: 입니다.
Location protocol: 입니다.
Location port: 입니다.
Location 객체 제어
3. Location 주요 속성 및 메서드 상세 분석
| 구분 / 속성명 | 사용 예시 (반환 형태) | 설명 및 특징 |
|---|---|---|
location.href |
"https://example.com/path/index.html" |
현재 문서의 전체 URL 주소 문자열을 반환합니다. 이 속성에 새로운 URL을 대입하면 페이지가 즉시 해당 주소로 이동합니다. |
location.hostname |
"example.com" |
웹 주소에서 도메인 이름(호스트 이름)만 추출하여 반환합니다. |
location.pathname |
"/path/index.html" |
도메인 뒤에 이어지는 파일 경로와 폴더 구조를 반환합니다. |
location.protocol |
"https:" 또는 "http:" |
웹 페이지에 접근할 때 사용된 통신 프로토콜(규약)을 반환합니다. |
location.port |
"80", "3000" 등 |
웹 서버가 사용 중인 포트 번호를 반환합니다. (기본 포트인 80이나 443의 경우 빈 문자열로 반환될 수 있음) |
location.assign() |
location.assign("주소") |
새로운 문서(URL)를 로드하여 페이지를 이동시킵니다. 브라우저의 세션 히스토리에 기록되므로 뒤로 가기가 가능합니다. |
핵심 정리
href, hostname, pathname 등을 통해 현재 웹 페이지의 주소 구성 요소를 세밀하게 파악location.assign() 또는 location.href = "주소"를 이용해 사용자 화면을 다른 페이지로 전환학습 포인트: `location` 객체를 통해 현재 문서의 URL 세부 속성을 읽어내고, 스크립트로 페이지 이동을 제어하는 방법을 익힙니다.