별초롱언니 2025. 4. 10. 16:46

location 객체는 현재 문서의 URL 정보를 포함하고 있으며, 웹브라우저의 주소 표시줄에 표시되는 URL을 조작하거나 정보를 얻는데 사용된다. 

 

특징정리

1. location 객체는 window에 속하는 하위객체이다. 

2. location 객체는 URL 정보를 가진다.

3. location 객체를 이용하여 페이지 이동이 가능하다. 

 

location 속성

속성 설명
host URL의 호스트 이름과 포트번호를 설정,반환한다
href 현재 페이지 URL 반환한다
hostname 웹 호스트의 도메인 이름 반환한다
pathname 현재 페이지의 경로와 파일 이름 반환한다
origin URL의 프로토콜, 호스트이름, 포트번호 반환한다
port URL의 포트번호를 설정, 반환한다
protocol 사용된 웹 프로토콜(http: 또는 https:)을 반환한다
assign() 새 문서를 로드한다
reload() 새로고침한다
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <button onclick="newDoc()">assign</button> <br>
  <script>
    document.write("Page location : " + location.href + "<br>");
    document.write("Page hostmane : " + location.hostmane + "<br>");
    document.write("Page pathname : " + location.pathname + "<br>");
    document.write("Page protocol : " + location.protocol + "<br>");

    function newDoc() {
      location.assign("https://www.naver.com");
    }
  </script>
</body>
</html>

assign 버튼 클릭하면 해당 url 새창 열림