JavaScript

JavaScript BOM

carrot62 2020. 7. 29. 15:50

Browser Object Model의 약자이다.

Window Methods

  • window
  • window.innerHeight
  • window.inner.Width
  • window.open()
  • window.close()
  • window.moveTo()
  • window.resizeTo()

Window Screen

  • screen.width
  • screen.height
  • screen.availWidth
  • screen.availHeight
  • screen.colorDepth
  • screen.pixelDepth

Window Location

현재 패이지에서 다른 페이지로 이동하고 싶을때(redirect browser) 사용한다. window.location을 사용할때 앞에 location을 생략해서 사용해도 된다.

  • window.location
    • href
    • hostname
    • pathname
    • protocol
    • port
    • assign()

예시)

<body>
	<p id="demo"></p>
</body>

<script>
	document.getElementById("demo").innerHTML= "Current window location is: " + window.location.href;
</script>
  • 새로운 페이지로 넘어가기- 많이 쓰이는 방법이니 잘 알아두도록 하자!
function goNewPage(){
	location.href="https://www.google.com/"
}

 

Window History

  • history.back(): 이전 url을 로딩해준다
  • history.forward()

뒤로가기 앞으로가기와 같은 역할을 한다

Window Navigator

  • navigator.appName: 사용중인 브라우저의 application 이름을 리턴한다
  • navigator.appCodeName
  • navigator.platform
  • navigator.product
  • navigator.userAgent
  • navigator.language
  • navigator.onLine
  • navigator.javaEnabled
  • navigator.cookiesenabled

Popup boxes

  • alert
window.alert("sometext");
  • confirm: 확인 버튼과 취소 버튼이 나오는 것이 특징이다
window.confirm("sometext");
//예시
function confirm1(){
            var txt="";
            if( confirm('Select a button')){
                txt = "You pressed OK";
            }
            else
                txt = "You pressed Cancel";
            
            document.getElementById('c1').innerHTML= txt;
        }

if문을 통해 확인 버튼을 누를때와 취소 버튼을 누를때의 action을 정할 수 있다.

  • prompt: 팝업화면에서 사용자로부터 입력값을 받는 방식이다.
function prompt1(){
            var txt="";
            var val= prompt('Enter your nickname: ', 'Harry Potter');
            if(val == null || val == ""){
                txt="User cancelled prompt."
            }
            else{
                txt="Hello, my nickname is " + val + "!";
            }
            document.getElementById('c2').innerHTML= txt;
}

Timing Events

window object에서 다음과 같은 timing 함수도 사용할 수 있다. 각 항목에 function을 넣을때 함수 이름만을 넣는다는 것을 기억하자. 괄호는 () 생략한다!

  • setInterval(function, milliseconds)
  • setTimeout(function, ,milliseconds)
  • clearTimeout(timeoutVariable)
  • clearInterval(timerVariable)

Browser Cookies

쿠키는 client 로컬 pc에 파일로 저장되어 있는 데이터이다. 

  • document.cookie
  • 쿠키 만드는 방법
document.cookie = "username=John Doe";
  • 쿠키에 파기날짜(expiry date, UTC time) 설정하기
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";
  • path를 이용해서 쿠키의 경로를 지정해주는 것도 가능하다
  • 쿠키 삭제하는 방법
    • 삭제할 value를 지정할 필요 없이 만료 날짜만 설정해주면 알아서 삭제된다 
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
  • 쿠키 읽어오는 방법
var x = document.cookie;
// 다음과 같은 형식으로 모든 쿠키를 불러오게 된다: cookie1=value; cookie2=value; cookie3=value;

특정 쿠키를 읽어오고 싶을때:

1. Function to set a cookie

getTime(): millisecond으로 시간을 리턴한다

.toUTCString(): 쿠키 유효날짜(expires string으로 만들어준다)로 설정해준다

function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  var expires = "expires="+ d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

2. Function to get a cookie

cookie가 cookie1=value; 형식으로 연달아서 저장되어 있기 때문에 split(';')를 이용해서 각 단위로 읽어 들인다.

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');	//semi colon단위로 ca라는 배열에 저장한다
  for(var i = 0; i <ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {	//찾고자 하는 쿠키값을 찾았다면
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

3. Function to check a cookie

function checkCookie() {
  var username = getCookie("username");	//getCookie 함수 미리 선언
  if (username != "") {
   alert("Welcome again " + username);
  } else {
    username = prompt("Please enter your name:", "");
    if (username != "" && username != null) {
      setCookie("username", username, 365);	//setCookie 함수 미리 선언
    }
  }
}