BOM | Browser Object Model

Ryan·2020년 10월 17일
0

BOM

목록 보기
1/1
post-thumbnail

Browser Object Mode이란 브라우저를 객체를 통해 제어하는 방법이다.
이중 객체란 윈도우(전역 객체)에 포함된 프로퍼티와 메서드들을 말한다.

1. alert

<!DOCTYPE html>
<html>
    <body>
        <input type="button" value="alert" onclick="alert('hello world');" />
    </body>
</html>
  • 알럿은 브라우저에 경고창을 띄우는 용도로 사용된다.
  • 알럿 코드가 사용중일 때에는 이후 코드는 실행되지 않는다. 확인을 누를때까지 멈춰있는다.

2. confirm

<!DOCTYPE html>
<html>
    <body>
        <input type="button" value="confirm" onclick="func_confirm()" />
        <script>
            function func_confirm(){
                if(confirm('ok?')){
                    alert('ok');
                } else {
                    alert('cancel');
                }
            }
        </script>
    </body>
</html>
  • 확인, 취소 버튼이 있는 알럿창과 비슷한 창을 띄울 수 있다.
  • 확인을 누를경우 불린의 true값을 반환하고 취소를 누를 경우 false값을 반환한다.

3. prompt

<!DOCTYPE html>
<html>
    <body>
        <input type="button" value="prompt" onclick="func_prompt()" />
        <script>
            function func_prompt(){
                if(prompt('id?') === 'egoing'){
                    alert('welcome');
                } else {
                    alert('fail');
                }
            }
        </script>
    </body>
</html>
  • 사용자로부터 입력값을 받을 수 있는 창을 생성할 수 있다.
  • 반환값은 사용자가 입력한 값이 된다.

4. location

1) location 객체

: 현재 위치의 주소를 찾아낼 수 있는 방법이다.

location.toString()
location.href
  • 두가지 모두 현재 URL을 반환한다.
console.log(location)
arlert(location)
  • 콘솔 로그로 로케이션을 찍어보면 로케이션 객체에 대한 내용을 확인할 수 있다.
  • location도 브라우저를 컨트롤 할 수 있는 하나의 객체란 것을 알 수 있다.
  • 그러나 알럿창으로 로케이션을 찍어보면 URL을 반환한다.
  • 알럿창은 브라켓 내부를 문자열로 인식해야하기 때문에 문자화 된 내용을 반환했기 때문이다.

2) location 프로퍼티

: 현재 문서의 다양한 정보를 알아낼 수 있는 프로퍼티를 사용할 수 있다.

console.log(location.protocol) // output: http//
  • 로케이션의 프로토콜 프로퍼티를 사용하면 현재 url의 프로퍼티가 어떤것이 사용되고 있는지 알려준다.
  • protocol, host, port, pathname(/이후), serch(?), hash(#)

3) url 다루기

location.href = 'url'; // url값으로 이동시켜준다.
location = 'url'; // 위와 동일
locarion.reload // 리로드 시킨다.

5. Navigator 객체

console.dir(navigator);
  • 위와 같은 명령을 통해 현재 페이지의 모든 프로퍼티를 열람할 수 있다.
  • appName : 브라우저 이름(크롬, 익스플로러, 파이어폭스 등)
  • appVersion : 브라우저의 버전
  • userAgent : 브라우저가 서버쪽으로 알려주는 유저 정보(앱버전과 같을수도 있음)
  • platform : 어디서 동작하고 있는지

6. Window 제어

  • window.open('주소') : 새창을 만든다
  • window.open('주소', '_self') : 지금 창에 띄운다.
  • window.open('주소', '_blank') : 새창
  • window.open('주소', '창이름') : 창이름이 붙은 창에가서 연다
  • window.open('주소', 'width=200, height=200, resizable=yes') : 창의 속성 입력

7. 크로스 브라우징 이슈에서 벗어나기

: 브라우저에 내장되어 있는 키를 사용하고, 없다면 기능테스트를 통해 해결한다.

if (!Object.keys) {
  Object.keys = (function () {
    'use strict';
    var hasOwnProperty = Object.prototype.hasOwnProperty,
        hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
        dontEnums = [
          'toString',
          'toLocaleString',
          'valueOf',
          'hasOwnProperty',
          'isPrototypeOf',
          'propertyIsEnumerable',
          'constructor'
        ],
        dontEnumsLength = dontEnums.length;
 
    return function (obj) {
      if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
        throw new TypeError('Object.keys called on non-object');
      }
 
      var result = [], prop, i;
 
      for (prop in obj) {
        if (hasOwnProperty.call(obj, prop)) {
          result.push(prop);
        }
      }
 
      if (hasDontEnumBug) {
        for (i = 0; i < dontEnumsLength; i++) {
          if (hasOwnProperty.call(obj, dontEnums[i])) {
            result.push(dontEnums[i]);
          }
        }
      }
      return result;
    };
  }());
}
profile
"꾸준한 삽질과 우연한 성공"

0개의 댓글