자바스크립트 Window 객체 정리
✅ 1. Window 객체란?
- 브라우저 창 전체를 대표하는 자바스크립트 객체
- window는 전역 객체이기 때문에 생략 가능
- 모든 전역 함수, 변수는 window의 속성이 됨
console.log(window.innerWidth); // 창 너비 확인
alert("Hello!"); // window.alert()와 동일
✅ 2. 브라우저 창 크기 얻기
var width =
window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
var height =
window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
console.log("너비:", width, "높이:", height);
innerWidth,innerHeight: 브라우저 뷰포트 크기- 구형 브라우저 대응을 위해
clientWidth도 함께 사용
✅ 3. 새 창 열기 – window.open()
var newWindow = window.open(
"https://example.com",
"팝업창이름",
"width=400,height=300,scrollbars=yes,resizable=yes"
);
| 옵션 속성 | 설명 |
|---|---|
| width, height | 창 너비와 높이 |
| left, top | 화면 위치 지정 |
| resizable | 창 크기 조절 허용 여부 |
| scrollbars | 스크롤 바 표시 여부 |
| menubar | 메뉴바 표시 여부 |
| location | 주소 표시줄 표시 여부 |
| status | 상태 표시줄 표시 여부 |
✅ 4. 새 창 닫기 – window.close()
newWindow.close();
- 단, 스크립트로 연 창에만 닫기 가능
- 사용자가 직접 연 창은 닫을 수 없음
✅ 5. 브라우저 위치 정보
console.log(window.screenX); // 창의 왼쪽 위치
console.log(window.screenY); // 창의 위쪽 위치
✅ 6. 전역 함수 = window 메서드
window.alert("안녕!"); // alert("안녕!")와 동일
window.setTimeout(...); // setTimeout(...), 생략 가능
✅ 7. 연결된 객체들
| 객체명 | 설명 |
|---|---|
window.document |
현재 문서(DOM 객체) |
window.location |
현재 URL, 페이지 이동 등 |
window.history |
브라우저 방문 기록 제어 |
window.navigator |
브라우저 정보 및 시스템 환경 정보 |
window.screen |
화면 해상도 정보 등 |
✅ 실습 예제: 팝업 창 열고 닫기
<button onclick="openPopup()">팝업 열기</button>
<button onclick="closePopup()">팝업 닫기</button>
<script>
let popup;
function openPopup() {
popup = window.open("https://example.com", "팝업", "width=500,height=400");
}
function closePopup() {
if (popup && !popup.closed) popup.close();
}
</script>
댓글남기기