이진욱의코딩

BOM에 대한 A to Z 본문

JS

BOM에 대한 A to Z

Crucifi 2019. 8. 27. 00:56

BOM(Browser Object Model)이란 웹브라우저의 창이나 프래임을 추상화해서 프로그래밍적으로 제어할 수 있도록 제공하는 수단이다. BOM은 전역 객체인 Window의 프로퍼티와 메서드들을 통해서 제어할 수 있다. 따라서 BOM에 대한 수업은 Window 객체의 프로퍼티와 메서드의 사용법을 배우는 것이라고 해도 과언이 아닐 것이다. 본 토픽의 하위 수업에서는 Window 객체의 사용법을 알아볼 것입니다.

 

 

 

 

※목록

 

----------------------------------------------------

1. 전역 객체 window

 

2. 사용자와 커뮤니케이션 하기

 

3. Location 객체

 

4. Navigator 객체

 

5. 창 제어

 

------------------------------------------------------

 

 

 

1. 전역 객체 window

 

window객체는 모든 객체가 소속된 객체이고, 전역 객체이면서, 창이나 프레임을 의미합니다.

먼저 예시를 한번 보도록 합시다.

 

<!DOCTYPE html>
<html>
<script>
    alert('Hello world');
    window.alert('Hello world');
</script>
<body>
 
</body>
</html>

 

window 객체의 메서드인 alert을 호출하는 방법에 대한 코드입니다.

 

window 객체는 식별자 window를 통해서 얻을 수 있습니다. 생략도 가능

 

<!DOCTYPE html>
<html>
<script>
    var a = 1;
    alert(a);
    alert(window.a);
</script>
<body>
 
</body>
</html>

이 코드는 전역 변수 a에 접근하는 방법입니다.

 

<!DOCTYPE html>
<html>
<script>
    var a = {id:1};
    alert(a.id);
    alert(window.a.id);
</script>
<body>
 
</body>
</html>

객체를 만든다는 것은 결국 window 객체의 프로퍼티를 만드는 것과 같습니다.

 

위의 예제를 통해서 알 수 있는 것은 전역 변수와 함수가 사실은 window 객체의 프로퍼티와 메서드라는 것입니다. 또한 모든 객체는 사실 window의 자식(?)이라는 것도 알 수 있습니다. 

 

웹 브라우저 자바스크립트에서 window 객체는 ECMAScript의 전역 객체이면서 동시에 웹브라우저의 창이나 프레임을 제어하는 역할을 합니다.

 

 

2. 사용자와 커뮤니케이션 하기

 

 

HTML은 form을 통해서 사용자와 커뮤니케이션할 수 있는 기능을 제공한다. 자바스크립트에는 사용자와 정보를 주고받을 수 있는 간편한 수단을 제공한다. 

 

-alert

 

->경고창이라고 부른다. 사용자에게 정보를 제공하거나 디버깅등의 용도로 많이 사용한다.

 

<!DOCTYPE html>
<html>
    <body>
        <input type="button" value="alert" onclick="alert('hello world');" />
    </body>
</html>

 

-confirm

 

->확인을 누르면 true, 취소를 누르면 false를 리턴한다.

 

<!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>

 

-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>

 

BOM모델의 사용자와의 커뮤니케이션 alert(), confirm(), prompt()...

 

 

3. Location객체

 

Location 객체는 문서의 주소와 관련된 객체로 Window 객체의 프로퍼티다. 이 객체를 이용해서 윈도의 문서 URL을 변경할 수 있고, 문서의 위치와 관련해서 다양한 정보를 얻을 수 있다.

 

 

-현재 윈도우의  url 알아내기

 

console.log(location.toString(), location.href);

 

4. Navigator 객체

 

Navigator 객체는 브라우저 호환성을 위해서 주로 사용하지만 모든 브라우저에 대응하는 것은 쉬운 일이 아니므로 아래와 같이 기능 테스트를 사용하는 것이 더 선호되는 방법이다. 

 

예를 들어 Object.keys라는 메서드는 객체의 key 값을 배열로 리턴하는 Object의 메서드다. 이 메서드는 ECMAScript5에 추가되었기 때문에 오래된 자바스크립트와는 호환되지 않는다. 아래의 코드를 통해서 호환성을 맞출 수 있다. 

 

// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
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;
    };
  }());
}

 

크로싱 브라우징 할 때 써야되는 객체로 볼 수 있다.

 

 

5. 창 제어

 

window.open 메소드는 새 창을 생성한다. 현대의 브라우저는 대부분 탭을 지원하기 때문에 window.open은 새 창을 만든다. 아래는 메서드의 사용법이다.

 

<!DOCTYPE html>
<html>
<style>li {padding:10px; list-style: none}</style>
<body>
<ul>
    <li>
        첫번째 인자는 새 창에 로드할 문서의 URL이다. 인자를 생략하면 이름이 붙지 않은 새 창이 만들어진다.<br />
        <input type="button" onclick="open1()" value="window.open('demo2.html');" />
    </li>
    <li>
        두번째 인자는 새 창의 이름이다. _self는 스크립트가 실행되는 창을 의미한다.<br />
        <input type="button" onclick="open2()" value="window.open('demo2.html', '_self');" />
    </li>
    <li>
        _blank는 새 창을 의미한다. <br />
        <input type="button" onclick="open3()" value="window.open('demo2.html', '_blank');" />
    </li>
    <li>
        창에 이름을 붙일 수 있다. open을 재실행 했을 때 동일한 이름의 창이 있다면 그곳으로 문서가 로드된다.<br />
        <input type="button" onclick="open4()" value="window.open('demo2.html', 'ot');" />
    </li>
    <li>
        세번재 인자는 새 창의 모양과 관련된 속성이 온다.<br />
        <input type="button" onclick="open5()" value="window.open('demo2.html', '_blank', 'width=200, height=200, resizable=yes');" />
    </li>
</ul>
 
<script>
function open1(){
    window.open('demo2.html');
}
function open2(){
    window.open('demo2.html', '_self');
}
function open3(){
    window.open('demo2.html', '_blank');
}
function open4(){
    window.open('demo2.html', 'ot');
}
function open5(){
    window.open('demo2.html', '_blank', 'width=200, height=200, resizable=no');
}
</script>
</body>
</html>

 

-새창에 접근

 

아래 예제는 보안상의 이유로 실제 서버에서만 동작하고, 같은 도메인의 창에 의해서만 작동한다.

 

<!DOCTYPE html>
<html>
<body>
    <input type="button" value="open" onclick="winopen();" />
    <input type="text" onkeypress="winmessage(this.value)" />
    <input type="button" value="close" onclick="winclose()" />
    <script>
    function winopen(){
        win = window.open('demo2.html', 'ot', 'width=300px, height=500px');
    }
    function winmessage(msg){
        win.document.getElementById('message').innerText=msg;
    }
    function winclose(){
        win.close();
    }
    </script>
</body>
</html>

 

-팝업차단

 

사용자의 인터렉션이 없이 창을 열려고 하면 팝업이 차단된다.

 

<!DOCTYPE html>
<html>
<body>
    <script>
    window.open('demo2.html');
    </script>
</body>
</html>

현시점에서는 alert를 많이 쓰지 않는다고 한다.

 

여기까지가 제가 오늘 공부한 부분입니다.

 

'JS' 카테고리의 다른 글

jQuery에 대해 알아봅시다.  (0) 2019.08.30
(DOM)제어 대상을 찾기  (0) 2019.08.27
DOM, BOM에 대해 알아봅시다.  (0) 2019.08.26
배열과 반복문  (0) 2019.07.27
배열과 반복문의 기초  (0) 2019.07.26