Front
[Javascript] location 객체 / history 객체 / navigator 객체
bkuk
2022. 9. 25. 23:39
location 객체
사용자 브라우저와 관련된 속성과 메서드를 제공하는 객체이며, 현재 URL에 대한 정보(속성)와 새로 고침(reload) 메서드를 제공
소스 코드
<script type="text/javascript">
// 페이지 내용 정보 확인
console.log( location );
// 사용자 브라우저의 URL 경로 값
console.log( location.href );
// URL의 호스트 이름과 포트 번호를 반환
console.log( location.host );
//URL의 호스트 이름을 설정 혹은 반환
console.log( location.hostname );
// URL의 프로토콜 반환
console.log( location.protocol );
</script>
console 출력
자동 경로 이동 (link)
redirection, 사용자 브라우저의 URL 경로를 지정한 URL 주소로 변경
소스 코드
<script type="text/javascript">
location.href = "https://www.daum.net";
</script>
클릭 시 지정한 URL로 이동하는 함수
소스 코드
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript">
const goURL = function(url){
location.href = url;
};
</script>
</head>
<body>
<a href="javascript:goURL('https://www.daum.net')">다음 바로가기</a></br>
<a href="javascript:goURL('https://www.naver.com')">네이버 바로가기</a></br>
</body>
</html>
"확인" 버튼을 누르면 지정한 URL로 이동하는 함수
소스 코드
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript">
const goURL2 = function(url) {
if( confirm('이동하시겠습니까?')){
location.href = url;
};
}
</script>
</head>
<body>
<a href="javascript:goURL2('https://www.daum.net')">다음 바로가기</a></br>
<a href="javascript:goURL2('https://www.naver.com')">네이버 바로가기</a></br>
</body>
history 객체
사용자가 방문한 사이트의 기록을 남기며, 이전 방문 사이트와 다음 방문 사이트로 다시 돌아갈 수 있는 속성과 메서드르 제공
종류 | 설명 |
history.goback() | 이전 방문 사이트로 이동 |
history.forward() | 다음 방문 사이트로 이동 |
history.go(이동 숫자) | 이동 숫자에 -2를 입력 시 2단계 이전의 방문 사이트로 이동 |
history.length | 방문 기록에 저장된 목록의 개수 반환 |
"이전페이지" 버튼을 누르면 이전 페이지로 이동
소스 코드
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript">
// history - goBack(이전페이지)
const goBack = function() {
history.back();
};
</script>
</head>
<body>
<a href="javascript:goBack('https://www.daum.net')">이전페이지</a></br>
</body>
navigator 객체
현재 방문자가 사용하는 브라우저의 정보와 운영체제 정보를 제공
종류 | 설명 |
navigator.appCodeName
|
현재 브라우저의 코드명 반환. 현 시점에서 모든 브라우저는 "Mozilla" 반환 |
navigator.appName
|
현재 브라우저의 이름 반환. 현 시점에서 모든 브라우저는 "Netscape" 반환 |
navigator.userAgent
|
브라우저와 운영체제의 종합 정보 제공 |
소스 코드
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript">
// navigator 객체
console.log(navigator.appCodeName);
console.log(navigator.appName);
console.log(navigator.userAgent);
</script>
</head>
<body>
</body>
console 출력