JS/JS (자바스크립트) ES5

JS (자바스크립트) Location, History, Navigator객체

0304호 2023. 1. 7.

location객체

Location 인터페이스는 객체가 연결된 장소(URL)를 표현한다.

URL파트

location 속성 설명
href URL전체
Protocol 프로토콜(Http, Https)
Host Hostname + Port
URL에 포트가 명시되지 않은 경우 Host와 Hostname은 동일값 반환
Hostname 도메인
Port 포트. 80, 443과 같이 연결 포트를 지정. 프로토콜이 http이면 80포트 생략 가능. 프로토콜이 https이면 443포트는 생략 가능.
Pathname 현재 실행 페이지. Path의 마지막 경로. "/"로 끝날 경우 서버에서 지정한 기본 페이지로 자동 지정되지만, 클라이언트인 자바스크립트에서는 비어있게 됨.
Origin Protocol + Hostname + Port 
Search Query String
Hash Anchcor

location객체의 함수 종류

1. 자바스크립트 페이지 이동 location.href = 주소;

DOM의 최상위 객체인 window객체에 바로 붙어있으므로

보통 window의 객체명은 생략할 수 있다.

아래의 함수도 window.location.href라고 사용하는 것이 정확하다.

<button onclick="move()">새로고침</button>

<script>       
function move(){
            location.href = "https://www.naver.com";       
}   
</script>

2. 자바스크립트 새로고침 location.reload()

<script>
1) 3초마다 새로고침        
setInterval(function(){
             location.reload();
},3000); 

2) 새로고침
window.location.reload(true);
</script>

history객체

History 인터페이스는 브라우저의 세션 기록, 즉 현재 페이지를 불러온 탭 또는 프레임의 방문 기록을 조작할 수 있는 방법을 제공한다.

  • 기록이동 : history.go(숫자); → 음수는 뒤로 이동, 양수는 앞으로 이동
  • 뒤로가기 : history.back();
  • 앞으로가기 : history.forward();
  • 페이지 데이터 : history.state;

목록 안에서 이동하는 것이 아니라 목록에 새로운 주소를 추가하는 메서드

  • history.pushState(저장할 데이터 객체, 바꿀 제목, 바뀐주소) : 페이지는 갱신되지 않았는데 주소만 바뀌고 페이지를 한 번 이동한 효과가 나타난다.
  • history.replaceState(저장할 데이터 객체, 바꿀 제목, 바뀐 주소) : 페이지 목록이 추가되는 것이 아니라 현재 페이지가 다른 페이지로 대체되는 효과가 나타난다.

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

 

History API - Web API | MDN

DOM의 Window 객체는 history 객체를 통해 브라우저의 세션 기록에 접근할 수 있는 방법을 제공합니다. history는 사용자를 자신의 방문 기록 앞과 뒤로 보내고 기록 스택의 콘텐츠도 조작할 수 있는,

developer.mozilla.org

함수 설명
history.go(-1); 기록이동
history.back(); 뒤로가기
history.replaceState(저장할데이터 , 바꿀제목 , 바뀐주소 );  새로운기록추가
history.state  페이지데이터

예시

DOM의 window객체는 history객체를 통해 브라우저의 히스토리에 접근할 수 있다.

사용자가 히스토리에서의 앞 뒤 이동이 가능하도록 메서드와 속성을 제공하며, history stack의 내용을 조작할 수 있게한다.

히스토리의 메서드

history.go(-1); //기록이동 (입력한 숫자만큼 이동하기 양수면 앞으로가기, 음수면 뒤로가기)

더보기
<!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>Document</title>
</head>
<body>
    1번페이지
    <button onclick="location.href = 'index06.html'">→</button>
</body>
</html>

history.back(); //한단계 뒤로가기

 

history.replaceState(저장할데이터 , 바꿀제목 , 바뀐주소 ); //브라우저의 기록을 변경

history 객체의 상태나 현재 history의 URL을 업데이트하려는 경우에 유용합니다.

기존에 있던 URL은 사라지고, 바뀐주소로만 뒤로가기가 가능하다.

 

+) history.pushState(저장할데이터, 바꿀제목, 기록주소URL) //브라우저 기록 추가

기존URL -> 기록주소URL -> 다음페이지URL

 

history.state //페이지데이터


Navigator 인터페이스는 사용자 에이전트의 상태와 신원 정보를 나타내며, 스크립트로 해당 정보를 질의할 때와 애플리케이션을 특정 활동에 등록할 때 사용한다.

함수 설명
appName()  브라우저 이름을 얻어옵니다
geolocation.getCurrentPosition()  현재 위치 정보를 얻어옵니다

예시

더보기
<!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>Document</title>
</head>
<body>
    
    <script>
        // console.log(navigator);

        var userAgent = navigator.userAgent.toLocaleLowerCase();

        console.log(userAgent);

        //사용자의 접속환경을 userAgent속성으로 확인할 수 있음
        if(userAgent.lastIndexOf("edg") != -1){
            console.log("엣지");
        } else if(userAgent.lastIndexOf("firefox") != -1) {
            console.log("파이어폭스");
        } else if(userAgent.lastIndexOf("whale") != -1){
            console.log("웨일");
        } else if (userAgent.lastIndexOf("chrome") != -1){
            console.log("크롬");
        }

    </script>

</body>
</html>

결과

 

예시

더보기
<!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>Document</title>
</head>
<body>
    
    <script>
        //console.log(navigator)
        //콜백 - 호출하면 다시 거기다가 내가 결과를 돌려줄게

        navigator.geolocation.getCurrentPosition(success, fail);

        function success(result){//위치정보 조회에 성공하면 success함수를 실행
            console.log(result.coords);
            console.log(result.coords.latitude);//위도
            console.log(result.coords.longitude);//경도
        }
        function fail(){//위치정보를 실패하면 fail함수를 실행
            console.log(result);
        }
    </script>
</body>
</html>

결과


콜백함수

파라미터로 함수를 전달받아 함수의 내부에서 실행하는 함수이다.

예시

더보기
<!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>Document</title>
</head>
<body>
    <h3>콜백함수</h3>

    <script>
        function geolocation(success, fail){
            //처리..... 몇초가 걸리지...?
            setTimeout(function(){
                //성공
                success("결과");
            },10000)
        }

        geolocation(success, fail);

        function success(result){
            console.log(result); //실행되는데 5초가 걸리고, 성공시에 result라는 변수로 결과를 받을 수 있음
        }

        function fail(result){

        }
    </script>
</body>
</html>

결과

10초가 지나면 결과 표시

 

댓글