[TCP School/자바스크립트] 브라우저 객체 모델(BOM) - Location 객체
location 객체는 현재 브라우저에 표시된 HTML 문서의 주소를 얻거나, 브라우저에 새 문서를 불러올 때 사용할 수 있다.
이 객체는 window 객체의 location 프로퍼티와 document 객체의 location 프로퍼티에 같이 연결되어 있다.
location 객체의 프로퍼티와 메소드를 이용하면, 현재 문서의 URL 주소를 다양하게 해석하여 처리할 수 있다.
현재 문서의 URL 주소
location 객체의 href 프로퍼티는 현재 문서의 전체 URL 주소를 문자열로 반환한다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>location.href</title>
</head>
<body>
<h1>현재 문서의 URL 주소</h1>
<script>
document.write('현재 문서의 URL 주소는 ' + location.href + '입니다.');
</script>
</body>
</html>
현재 문서의 호스트 이름
location 객체의 hostname 프로퍼티는 현재 문서의 인터넷 호스트 이름을 반환한다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>location.hostname</title>
</head>
<body>
<h1>현재 문서의 호스트 이름</h1>
<script>
document.write('현재 문서의 호스트 이름은 ' + location.hostname + '입니다.');
</script>
</body>
</html>
서버에 연결되어 있는 파일이 아니기 때문에 호스트 이름이 나오지 않는다.
현재 문서의 파일 경로명
location 객체의 pathname 프로퍼티는 현재 문서의 파일 경로명을 반환한다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>location.pathname</title>
</head>
<body>
<h1>현재 문서의 파일 경로명</h1>
<script>
document.write('현재 문서의 파일 경로명은 ' + location.pathname + '입니다.');
</script>
</body>
</html>
현재 창에 문서 불러오기
location 객체의 assign() 메소드는 브라우저 창에 지정된 URL 주소에 존재하는 문서를 불러온다.
반면에 replace() 메소드는 새 문서를 불러오기 전에, 현재 문서를 브라우저의 히스토리에서 제거한다는 차이점이 있다.
location 객체의 reload() 메소드는 브라우저 창에 현재 문서를 다시 불러온다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>location.assign, location.replace</title>
</head>
<body>
<h1>현재 창에 문서 불러오기</h1>
<p>아래 버튼을 눌러 새로운 문서를 연 뒤 브라우저의 뒤로가기 버튼 누르기</p>
<button onclick="openDocument()">새로운 문서 열기</button>
<button onclick="openDocumentWithReplace()">이전 문서 삭제 후 새로운 문서 열기</button>
<script>
function openDocument() {
location.assign('http://www.tcpschool.com/index.php');
}
function openDocumentWithReplace() {
location.replace('http://www.tcpschool.com/index.php');
}
</script>
</body>
</html>
TCP School의 강의 내용을 정리한 포스트입니다.
http://www.tcpschool.com/javascript/intro
코딩교육 티씨피스쿨
4차산업혁명, 코딩교육, 소프트웨어교육, 코딩기초, SW코딩, 기초코딩부터 자바 파이썬 등
tcpschool.com
'공부 > JavaScript' 카테고리의 다른 글
[TCP School/자바스크립트] 브라우저 객체 모델(BOM) - Screen 객체 (0) | 2023.04.25 |
---|---|
[TCP School/자바스크립트] 브라우저 객체 모델(BOM) - History 객체 (0) | 2023.04.25 |
[TCP School/자바스크립트] 브라우저 객체 모델(BOM) - Window 객체 (0) | 2023.04.25 |
[TCP School/자바스크립트] 문서 객체 모델(DOM) - 노드의 조작 (0) | 2023.04.25 |
[TCP School/자바스크립트] 문서 객체 모델(DOM) - 노드의 관리 (0) | 2023.04.24 |