window 객체 완벽 가이드웹 브라우저 환경에서 자바스크립트를 실행할 때 가장 기본이 되는 전역
객체가 바로 window 객체입니다.
브라우저에서 실행되는 모든 전역 변수와 함수는 사실상 window 객체의
속성으로 등록되며,
DOM 조작, 브라우저 제어, 이벤트 처리 등 다양한 기능을 제공합니다.
window 객체란?global 객체가 전역이지만, 브라우저에서는
window가 전역 객체 역할을 합니다.window 객체의 속성으로
등록됩니다.var globalVar = "Hello";
console.log(window.globalVar); // "Hello"this 키워드가 전역에서 참조될 경우 window를 가리킵니다.type="module")에서는 undefined가 되므로 차이가
있습니다.window.location
console.log(window.location.href); // 현재 페이지의 전체 URL
window.location.href = "https://example.com"; // 페이지 이동window.history
back(), forward(), go(n) 같은 메서드를 제공합니다.history.back(); // 뒤로가기
history.forward(); // 앞으로가기
history.go(-2); // 2단계 뒤로 이동window.navigator
console.log(navigator.userAgent); // 브라우저/OS 정보
console.log(navigator.language); // 언어 설정window.document
document.title = "새 제목";
document.body.style.background = "lightgray";window.screen
console.log(screen.width, screen.height); // 화면 해상도alert(), confirm(), prompt()
alert("Hello, World!");
if (confirm("삭제하시겠습니까?")) {
console.log("삭제 실행");
}
let name = prompt("이름을 입력하세요:");open()
let newWin = window.open("https://example.com", "_blank", "width=500,height=400");setTimeout / clearTimeout
let timer = setTimeout(() => console.log("3초 후 실행"), 3000);
clearTimeout(timer);setInterval / clearInterval
let interval = setInterval(() => console.log("1초마다 실행"), 1000);
clearInterval(interval);pushState()와 replaceState()를 사용하면 브라우저 주소 표시줄을
바꾸면서도 페이지 전체 새로고침 없이 화면을 전환할 수 있습니다.history.pushState({ page: 1 }, "title 1", "?page=1");
history.replaceState({ page: 2 }, "title 2", "?page=2");
window.onpopstate = function(event) {
console.log("뒤로가기/앞으로가기 이벤트", event.state);
};postMessage)// 부모 창
let child = window.open("child.html");
child.postMessage("Hello Child", "*");
// 자식 창 (child.html)
window.addEventListener("message", (event) => {
console.log("부모에서 받은 메시지:", event.data);
});window.localStorage, window.sessionStorage를 통해 키-값 저장소
활용 가능.localStorage.setItem("user", "Alice");
console.log(localStorage.getItem("user")); // "Alice"window.open()은 사용자 액션(클릭 등) 없이 호출하면
대부분 브라우저에서 차단됩니다.window 객체 접근은 제한됩니다.window에 직접 올리는 대신 let,
const 사용으로 스코프를 제한하는 것이 바람직합니다.strict mode에서 this는
window를 가리키지 않을 수 있습니다.window는 브라우저 환경의 전역 객체이며, DOM, 네비게이션, 타이머,
팝업, 저장소 등 다양한 기능을 제공.history.pushState 같은 API는 SPA 라우팅 구현에 핵심적.