JavaScript

21. Location 객체

HJ76 2023. 4. 7. 17:12
Location 객체
  • 현재 브라우저에 표시된 HTML 문서의 주소를 얻거나, 브라우저에 새 문서를 불러올 때 사용
카카오 홈페이지 예시

Location 객체의 속성
protocol
  • 콜론을 포함하는 http, https, ftp 등 프로토콜 정보를 반환
hostname
  • 호스트의 이름가 포트번호를 반환
pathname
  • URL 경로 부분의 정보를 반환
href
  • 페이지 URL 전체 정보를 반환 또는 URL을 지정하여 페이지를 이동
protocol
  • 콜론을 포함하는 http, https, ftp 등 프로토콜 정보를 반환
reload()
  • 페이지 새로고침(F5)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Location 객체</title>
</head>
<body>
    <h2>Location 객체</h2>
    <script>
        console.log(`현재 문서의 URL 주소: ${location.href}`); // 현재 문서의 URL 주소: http://127.0.0.1:5500/1.Location.html
        console.log(`현재 문서의 protocol: ${location.protocol}`); // 현재 문서의 protocol: http:
        console.log(`현재 문서의 hostname: ${location.hostname}`); // 현재 문서의 hostname: 127.0.0.1
        console.log(`현재 문서의 pathname: ${location.pathname}`); // 현재 문서의 pathname: /1.Location.html
        
        // location.href를 이용하여 파이썬 홈페이지로 이동
        function sendit() {
            location.href = 'https://python.org';
        }
    </script>
    <p><button onclick="location.reload()">새로고침</button></p>
    <p><button onclick="sendit()">이동</button></p>
</body>
</html>