본문 바로가기
프로그래밍/예제로 배우는 자바스크립트 요약 및 분석(IT 전공 서적)

예제로 배우는 자바스크립트 요약 및 코드 분석 13장 13.5~13.7

by 리드민 2023. 10. 19.
반응형

13.5 History 객체

  History 객체는 브라우저에 방문한 기록, 즉 히스토리 목록을 저장하고 관리하는 데 사용된다. 자바스크립트에서는 사용자의 개인 정보 보호를 위해 이 객체에 접근할 수 있는 권한이 일부 제한된다. History 객체의 length 프로퍼티와 back(), forward(), go() 메서드를 이용하여 히스토리 목록에 저장된 URL 주소의 개수를 얻고 히스토리 목록에 있는 특정 URL로 이동할 수 있다.

 

13.5.1 히스토리 목록 개수 알아보기

  History 객체의 length 프로퍼티는 히스토리 목록에 저장된 URL 주소의 개수를 얻는 데 사용된다.

예제 13-12.History 객체의 length 프로퍼티 history_length.html 코드 원문
<p id="show"></p>
<script>
    document.getElementById("show").innerHTML = history.length;
</script>
예제 13-12.History 객체의 length 프로퍼티 history_length.html 코드 분석
<p id="show"></p>
<script>
    document.getElementById("show").innerHTML = history.length;
</script>

 

history.length는 현재 히스토리 목록에 저장된 URL 주소를 가져오는 데 사용된다. 현재 히스토리는 6개의 URL이 저장되어 있다는 것을 알 수 있다.

 

13.5.2 히스토리 목록 접근하기

  저장된 히스토리 목록에 접근하기 위해서 History 객체에서는 go(), back(), forward() 세 개의 메서드를 제공한다.

예제 13-13. 히스토리 목록에 접근하기 history_go.html 코드 원문
<button onclick="goPage()">2 페이지 이전</button><br>
<script>
    function goPage() {
        history.go(-2);
    }
</script>
예제 13-13. 히스토리 목록에 접근하기 history_go.html 코드 분석
<button onclick="goPage()">2 페이지 이전</button><br>
// 버튼을 클릭하면 onclick 이벤트로 goPage() 메서드 사용
<script>
    function goPage() {
    // goPage() 메서드 선언
        history.go(-2);
    }
</script>

 

13.6 Navigator 객체

  Navigator 객체는 브라우저에 관련된 정보를 담고 있는 객체이다. Navigator 객체의 프로퍼티를 이용하여 브라우저의 종류, 버전, 사용 언어, 플랫폼 등 브라우저 관련 정보를 얻을 수 있다.

예제 13-14. Navigator 객체의 프로퍼티 navigator.html 코드 원문
<p id="show"></p>
<script>
    let text = "";
    text += "-appCodeName 프로퍼티: " + navigator.appCodeName + "<br>";
    text += "-appName 프로퍼티: " + navigator.appName + "<br>";
    text += "-appVersion 프로퍼티" + navigator.appVersion + "<br>";
    text += "-language 프로퍼티" + navigator.language + "<br>";
    text += "-platform 프로퍼티" + navigator.platform + "<br>";
    text += "-cookieEnabled 프로퍼티" + navigator.cookieEnabled + "<br>";
    text += "-online 프로퍼티" + navigator.onLine + "<br>";
    text += "-userAgent 프로퍼티: " + navigator.userAgent;
    document.getElementById("show").innerHTML = text;
</script>
예제 13-14. Navigator 객체의 프로퍼티 navigator.html 코드 분석
<p id="show"></p>
<script>
    let text = "";
    text += "-appCodeName 프로퍼티: " + navigator.appCodeName + "<br>";
    text += "-appName 프로퍼티: " + navigator.appName + "<br>";
    text += "-appVersion 프로퍼티" + navigator.appVersion + "<br>";
    text += "-language 프로퍼티" + navigator.language + "<br>";
    text += "-platform 프로퍼티" + navigator.platform + "<br>";
    text += "-cookieEnabled 프로퍼티" + navigator.cookieEnabled + "<br>";
    text += "-online 프로퍼티" + navigator.onLine + "<br>";
    text += "-userAgent 프로퍼티: " + navigator.userAgent;
    document.getElementById("show").innerHTML = text;
</script>

Navigator 객체의 프로퍼티들을 표로 정리하면 다음과 같다.

Navigator 객체의 프로퍼티
프로퍼티 설명
appCodeName 브라우저 코드 이름
appName 브라우저 이름
appVersion 브라우저 버전
language 브라우저 언어
platform 브라우저가 실행되는 운영체제
cookieEnabled 쿠키 사용 여부
onLine 브라우저 온라인 여부
userAgent 브라우저가 서버에 보낸 브라우저 관련 user-agent 헤더 정보

 

13.7 타이머 메서드

  자바스크립트를 사용할 때 페이지가 로드되거나 버튼이 클릭되었을 때 특정 함수를 실행하지 않고, 약간의 시간이 경과된 후에 실행되게 하고 싶을 때가 종종 있다. 이럴 때 사용하는 것이 바로 타이머(timer) 메서드이다.

자바스크립트에서 타이머 메서드는 다음의 두 가지가 있다.

1. setTimeout() : 밀리초가 경과된 후 특정 함수 실행

2. setInterval() : setTimeout()과 같이 동작하지만 특정 함수를 반복 실행

  setTimeout()과 setInterval() 메서드는 둘 다 Window 객체의 메서드이다. 따라서 이 메서드들은 window.setTimeout()과 window.setInterval()과 같은 형태로 사용된다. 그러나 앞에서 설명한 것과 같이 Window 객체의 메서드는 전역 함수이기 때문에 앞에 붙는 'window'를 생략하여 setTimeout()과 setInterval()로 많이 사용된다.

 

13.7.1 setTimeout() 메서드

  setTimeout() 메서드를 이용하여 버튼을 클릭한 다음 2초 후에 특정 함수가 실행되게 한다.

예제 13-15. setTimeout() 메서드 사용 예 set_timeout.html 코드 원문
<button onclick="setTimeout(func1, 2000)">2초 후 실행</button>
<script>
    function func1() {
        alert("안녕하세요.");
    }
</script>
예제 13-15. setTimeout() 메서드 사용 예 set_timeout.html 코드 분석
<button onclick="setTimeout(func1, 2000)">2초 후 실행</button>
// button onclick 이벤트 사용
<script>
    function func1() {
    // 사용자 정의 함수 func1() 선언
        alert("안녕하세요.");
    }
</script>

 

setTimeout() 메서드에 의해 실행된 함수를 중간에 중지시키려면 다음 예에서와 같이 clearTimeout() 메서드를 사용한다.

예제 13-16. clearTimeout() 메서드 사용 예 clear_timeout.html 코드 원문
<button onclick="execFunc = setTimeout(func1, 3000)">3초 후 실행</button>
<button onclick="clearTimeout(execFunc)">실행 중지</button>
<script>
function func1() {
    alert("안녕하세요.");
}
</script>
예제 13-16. clearTimeout() 메서드 사용 예 clear_timeout.html 코드 원문
<button onclick="execFunc = setTimeout(func1, 3000)">3초 후 실행</button>
<button onclick="clearTimeout(execFunc)">실행 중지</button>
// onclick 이벤트 실행 clearTimeout(execFunc) 함수 실행
<script>
function func1() {
// 함수 func1() 선언
    alert("안녕하세요.");
}
</script>

 

13.7.2 setInterval() 메서드

  setInterval() 메서드는 주어진 시간 간격마다 특정 함수를 실행하는 데 사용된다.

예제 13-17. setInterval() 메서드 사용 예 set_interval.html 코드 원문
<p id="show"></p>
<script>
    setInterval(func1, 1000);

    function func1() {
        const d = new Date();
        document.getElementById("show").innerHTML = d;
    }
</script>
예제 13-17. setInterval() 메서드 사용 예 set_interval.html 코드 원문
<p id="show"></p>
<script>
    setInterval(func1, 1000);
    // setInterval(func1, 1000)은 func1()을 1000 밀리초, 1초 간격으로 실행한다.

    function func1() {
    // 함수 func1() 선언
        const d = new Date();
        document.getElementById("show").innerHTML = d;
    }
</script>

 

clearInterval() 메서드는 다음 에에서와 같이 setInterval()에 의해 반복 실행 중인 함수를 중지시키는데 사용된다.

예제 13-18. clearInterval() 메서드 사용 예 clear_interval.html 코드 원문
<button onclick="clearInterval(execTimer)">타이머 중지</button>
<script>
    let execTimer = setInterval(func1, 1000);
    function func1() {
        const d = new Date();
        document.getElementById("show").innerHTML = d;
    }
</script>
예제 13-18. clearInterval() 메서드 사용 예 clear_interval.html 코드 원문
<button onclick="clearInterval(execTimer)">타이머 중지</button>
<script>
    let execTimer = setInterval(func1, 1000);
    function func1() {
    // 사용자 함수 func1() 선언
        const d = new Date();
        document.getElementById("show").innerHTML = d;
    }
</script>

 

 
반응형