본문 바로가기
Web/JavaScript

[JavaScript] 객체 - 6️⃣Location 객체 & Location객체 함수

by coding-choonsik 2023. 4. 12.
728x90
반응형
SMALL

1. Location객체

  • 현재 브라우저에 표시된 HTML 문서의 주소를 얻거나, 브라우저에 새 문서를 불러올 때 사용

 

 

2. Location 객체 메서드

  •  protocol: 콜론을 포함하는 http, https, ftp 등 포로토콜 정보를 반환
  •  hostname: 호스트의 이름과 포트번호를 반환
  •  pathname: URL 경로부분의 정보를 반환
  •  href: 페이지 URL 전체 정보를 반환 또는 URL을 지정하여 페이지를 이동
  • reload(): 새로고침 버튼처럼 현재를 다시 불러옴

<!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}`)   
        console.log(`현재 문서의 protocol: ${location.protocol}`)  //http:
        console.log(`현재 문서의 protocol: ${location.hostname}`)  // 127.0.0.1 (내 컴퓨터 ip)
        console.log(`현재 문서의 protocol: ${location.pathname}`)  //1_location.html
	
    	// 버튼 onclick이벤트로 주어질 함수
        // 주어진 링크로 이동
        function sendit(){
            location.href = 'https://coding-yesung.tistory.com/';
        }
    </script>
    <p><button onclick="sendit()">이동</button></p>
    <p></p>
</body>
</html>

 

▲ 현재 문서의 location 객체 정보

 

 

▲ 버튼 클릭 후 href 메서드에서 주어진 링크로 이동이 잘 된다.


MDN: Location

https://developer.mozilla.org/ko/docs/Web/API/Location

 

Location - Web API | MDN

Location 인터페이스는 객체가 연결된 장소(URL)를 표현합니다. Location 인터페이스에 변경을 가하면 연결된 객체에도 반영되는데, Document와 Window 인터페이스가 이런 Location을 가지고 있습니다. 각각

developer.mozilla.org

 

728x90
반응형
LIST