JS | BOM - location 객체, history 객체

2023. 1. 5. 11:22·JavaScript

location 객체

자바스크립트 페이지 이동
location.href = 주소
자바스크립트 새로고침
location.reload()


location 객체 사용

<button occlikc="move()">새로고침</button>
<script>
        function move(){
            location.href ="https://www.naver.com";
        }
        //3초마다 새로고침
        // setInterval(function(){
        //     location.reload();
        // },3000);
</script>

 


history 객체

브라우저의 기록을 할 수 있는 객체 ex)뒤로가기, 앞으로가기

history.go(숫자);  : 기록 이동

history.back(); : 뒤로가기

history.pushState(null, '', '변경.html'); : 새로운 기록 추가

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

ex)뒤로 갔을때 alert를 하지 않아야 할 때 사용

ex ) list ->  등록 -> 결과 (등록이 잘 완료되었다면 뒤로가기 눌렀을 때 list 페이지를 보여줌)

https://developer.mozilla.org/ko/docs/Web/API/History/replaceState

 

history.state  : 페이지데이터

 


history 객체 사용 

 

예제 1 ) 

(1) 페이지 이동 클릭 -> (2) 뒤로가기-> (3) 본래 페이지로 이동

1p 코드

  1p
    <button onclick = "location.href = 'index6.html'">페이지이동</button>
    

    <h3>리플레이스 스테이트</h3>
    <button onclick = "func()">기록변경</button>

    <script>
        function func(){
            // history.pushState(null, '', '변경.html'); //브라우저 기록 추가
            //페이지 이동이 아님. 기록을 추가하는 것.
            history.replaceState('','', null); //브라우저의 기록을 변경
        }

        //기록을 변경해서 사용할 데이터를 '' 바꿔주면,사용자가 뒤로가기 버튼을 누른것을 감지할 수 있다.
        //history.state 속성으로 확인이 가능함
        if(history.state == ''){
            alert("기록이 변경됨");
        }
        
    </script>

2p 코드

2p
<button onclick = "history.go(-1)">뒤로가기</button>

 

예제 2 ) 

 

 

 


navigator 객체

사용자의 접속환경을 감지할 수 있는 어떤 브라우저로 접속을 했는가 브라우저의 버전은 몇인지 엔진 정보 등등

 

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

 

console.log(navigator);

"Netscape" : 초창기 브라우저 이름

 


navigator 객체 사용 

 

예제 1 ) userAgent 사용하여 브라우저 종류 확인

 var userAgent = navigator.userAgent.toLowerCase();

        console.log(userAgent);
        //mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/108.0.0.0 safari/537.36

        if(userAgent.lastIndexOf("edg") > 0){
            console.log("엣지");
        } else if(userAgent.lastIndexOf("firefox") > 0){
            console.log("파이어폭스");
        } else if(userAgent.lastIndexOf("chrome") > 0){
            console.log("크롬");
        } else if(userAgent.lastIndexOf("whale") > 0){
            console.log("웨일");
        }

 

예제 2 ) geolocation.getCurrentPosition() 사용하여 현재 위치 확인

// 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(result) { //위치정보를 실해하면 fail함수를 실행
     console.log(result);
}

 

'JavaScript' 카테고리의 다른 글

JS | 쿠키(🍪cookie)  (0) 2023.01.05
JS | 콜백함수 (매우중요)  (0) 2023.01.05
JS | BOM - 윈도우객체  (0) 2023.01.04
JS | 날짜 객체  (0) 2023.01.04
JS | form 객체  (0) 2023.01.04
'JavaScript' 카테고리의 다른 글
  • JS | 쿠키(🍪cookie)
  • JS | 콜백함수 (매우중요)
  • JS | BOM - 윈도우객체
  • JS | 날짜 객체
개발 공부
개발 공부
  • 개발 공부
    개발 공부
    개발 공부
  • 전체
    오늘
    어제
    • 전체보기 (163)
      • 프로젝트 (1)
      • JavaScript (46)
      • Node.js (3)
      • Next.js (5)
      • React (17)
      • NoSQL (0)
      • HTML,CSS (3)
      • CS (6)
      • Java (35)
      • Spring (6)
        • Spring의 정석 (1)
      • Spring boot (1)
      • MySQL (1)
      • 리눅스 (16)
      • JSP (9)
      • AWS (0)
      • git (2)
      • 알고리즘 (1)
      • ect (7)
      • Project (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    자바의 정석
    Java
    자바
    티스토리챌린지
    오블완
    Java의 정석
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
개발 공부
JS | BOM - location 객체, history 객체
상단으로

티스토리툴바