전역객체 window
모두 window 객체에 속해 있다.
123을 출력하는 경고창.
<script>
function alertfnc(){
alert(1);alert(2);alert(3);
} </script>
<input type="button"
value="confirm" onclick = "alertfnc();"/>
<script>
function alertfnc(){
if(confirm('확인')){
alert('확인');
}else{
alert('취소'); } }
확인과 취소를 묻는 확인창.
prompt('이름은?'); 이름을 묻는 입력창이 뜨고 이름을 입력하면,
'민기' -- 이름이 출력된다.
<input type="button"
value="prompt" onclick = "alertfnc();"/>
<script>
function alertfnc(){
if(prompt('이름?')==='민기'){
alert('확인');
}else{
alert('취소');}}
이름을 확인해서 맞으면 확인, 아니면 취소를 출력하는 입력창.
location객체가 가지는 다양한 프로퍼티들.
console.log(location.protocol, location.host, location.port, location.pathname, location.search, location.hash)
현재 문서를 이동시키는 법.
location.href = 'http://egoing.net'; 혹은.
location = 'http://egoing.net';
문서를 리로드 하는 법.
location.reload();
브라우저의 정보를 제공하는 객체, 호환성 문제를 위해서 사용.
객체의 모든 프로퍼티를 열람할 수 있는 코드.
console.dir(navigator);
내비게이터에 앞서 크로스 브라우징(cross browsing)에 대해 알아봐야 한다.
수많은 브라우저들이 있는 지금. 브라우저마다 같은 코드가 다른 결과를 낼 수 있으므로 브라우저의 특성을 체크해서 코드를 고쳐야하고 이러한 문제가 크로스 브라우징 이슈고 이를 해결하는 게 내비게이터 객체다.
주요한 프로퍼티를 알아보자.
appName
웹브라우저의 이름이다. IE는 Microsoft Internet Explorer, 파이어폭스, 크롬등은 Nescape로 표시한다.
appVersion
브라우저의 버전을 의미한다. 현재 브라우저 정보는 아래와 같다.
appVersion: "5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36"
userAgent
브라우저가 서버측으로 전송하는 USER-AGENT HTTP 헤더의 내용이다. appVersion과 비슷하다.
userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36"
브라우저가 동작하고 있는 운영체제에 대한 정보다.
platform
"Win32"
예를 들어 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;
};}());}
window.open은 새 창 생성.
demo2.html파일을 새탭으로 열도록 하는 코드
<!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>
이렇게 창이 뜬다.
세번째 인자(창의 모양)로 나타난 창의 모양
200,200 크기의 창.
_self _blank는 약속된 값, self는 자기자신, blank는 새로운 창.
<!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');
전역변수 win에 새창의 정보가 담기게 된다.
} open 버튼을 만든다.
function winmessage(msg){
win.document.getElementById('message').innerText=msg;
}사용자가 글을 타이핑해서 보내는 텍스트 필드를 생성
function winclose(){
win.close();
}
</script>
</body>
</html>