JS window 是瀏覽器裡 JavaScript 腳本的全域物件,它是 Window 介面的實例。MDN 說明,Window 介面代表一個含有 DOM 文件的視窗,window.document 指向視窗裡載入的文件。
分頁式瀏覽器裡,每個分頁都有自己的 Window 物件,腳本裡的 window 永遠是它所在的那個分頁。Window 也放了大量需要全域取用的函式、物件與建構子,即使它們和「視窗」本身沒有直接關係。
本篇整理 window 的角色、常用成員與事件。document 物件另有專文(JS document 物件總覽),window.location 的各個屬性請看站上的 window.location 屬性整理,window.localStorage 請看站上的 localStorage 用法,window.postMessage() 的跨來源安全另有專文。
window 是什麼:全域物件與它的別名
瀏覽器腳本頂層可以直接用 window,它指向目前這個視窗,也是全域物件。下面這幾種寫法取得的是同一個物件:
console.log(window === globalThis); // true
console.log(window === self); // true
console.log(window === window.window); // true
console.log(window === document.defaultView); // true
console.log(window.document === document); // true
| 寫法 | 說明 |
|---|---|
window、window.window | 瀏覽器視窗環境專用 |
self | 視窗環境指向 window;在 Web Worker 裡指向 Worker 的全域範圍,所以跨環境時更通用 |
globalThis | ECMAScript 的標準寫法,在視窗、Worker 與非視窗環境都能用 |
document.defaultView | 從文件取回對應的 window |
MDN 說明,window 與 self 在 Web Worker 裡不同:Worker 沒有 window,只有 self。在 Node.js 裡 window 與 self 都不能用,要改用 global,或直接用 globalThis:
// Node.js
console.log(typeof window); // undefined
console.log(globalThis === global); // true
// Web Worker 內
console.log(typeof window); // undefined
console.log(typeof self); // object
console.log(self === globalThis); // true
瀏覽器裡 globalThis 是 WindowProxy
MDN 補充:瀏覽器的 globalThis 實際上指向一層 WindowProxy,包著真正的全域物件,原因是 iframe 與跨視窗的安全考量。一般使用上幾乎不會察覺差別。
頂層的 var 會變成 window 的屬性,let 與 const 不會
在一般的 <script>(classic script)頂層,用 var 宣告的變數會成為全域物件的屬性,函式宣告同樣會出現在 window 上。MDN 說明,var 建立的屬性是不可設定(non-configurable)的,不能用 delete 刪除。let 在 script 頂層不會在全域物件上建立屬性,const 也一樣:
<script>
var legacy = 1;
let modern = 2;
const fixed = 3;
function hello() {}
console.log(window.legacy); // 1
console.log(window.modern); // undefined
console.log(window.fixed); // undefined
console.log("legacy" in window); // true
console.log("modern" in window); // false
console.log(typeof window.hello); // function
console.log(delete window.legacy); // false
</script>
直接指定 window.manual = 5 建立的屬性則可以刪除,刪除後 manual 就不存在了:
window.manual = 5;
console.log(manual); // 5
console.log(delete window.manual); // true
console.log(typeof manual); // undefined
MDN 另外說明,在原生 ES 模組(<script type="module">)裡,頂層宣告的作用域屬於模組本身,不會加到全域物件:
<script type="module">
var moduleVar = 1;
console.log("moduleVar" in window); // false
console.log(this); // undefined
</script>
具名屬性:id 與 name 也會出現在 window 上
MDN 列出一種容易忽略的行為,叫具名屬性(named properties):
<embed>、<form>、<iframe>、<img>、<object>元素有非空的name時,這個name會成為window的屬性。- 任何 HTML 元素有非空的
id時,這個id也會成為window的屬性。
<div id="box">box</div>
<form name="signup"></form>
console.log(window.box === document.getElementById("box")); // true
console.log(window.signup === document.forms.signup); // true
console.log(window.signup.tagName); // FORM
一個屬性對應到多個元素時,回傳 HTMLCollection。這個機制了解即可,要取得元素時,用 document.getElementById() 這類明確的方法比較不容易搞混。
常用屬性
MDN 的 Window 頁面列出非常多屬性,下面挑常用的,依用途分類。其中多數是唯讀屬性,不能指定新值:
| 類別 | 屬性 | 說明 |
|---|---|---|
| 文件與導覽 | document、location、history、navigator | 目前文件、網址、瀏覽歷史、瀏覽器資訊 |
| 儲存 | localStorage、sessionStorage、indexedDB、caches | 各種前端儲存;caches 只在安全環境(secure context)可用 |
| 尺寸 | innerWidth、innerHeight、outerWidth、outerHeight、devicePixelRatio | 視窗與顯示器的尺寸、像素比 |
| 捲動 | scrollX、scrollY | 文件目前捲動的像素數;pageXOffset、pageYOffset 是別名 |
| 框架關係 | frames、length、parent、top、frameElement、opener | 子框架與上層視窗 |
| 其他 | name、closed、screen、isSecureContext、crypto、performance、customElements | 視窗名稱、是否已關閉、螢幕資訊等 |
location 與 name 不是唯讀屬性,可以讀也可以指定新值。
視窗尺寸與捲動
innerWidth 與 innerHeight 是視窗版面視口(layout viewport)的寬與高,單位是像素。MDN 說明,innerWidth 包含垂直捲軸的寬度(有顯示捲軸時),innerHeight 包含水平捲軸的高度。
想取得扣掉捲軸與邊框的寬度,MDN 建議改讀根元素 <html> 的 clientWidth。outerWidth 與 outerHeight 則是整個瀏覽器視窗外緣的尺寸,包含側邊欄、工具列與邊框。
devicePixelRatio 是實體像素與 CSS 像素的比值。MDN 說明,值為 1 代表傳統 96 DPI 的顯示器,HiDPI/Retina 顯示器預期是 2;頁面縮放會改變這個值,雙指縮放(pinch-zoom)則不會。
假設瀏覽器視窗的版面視口是 800 × 600、頁面高度超過視窗,讀取尺寸與捲動位置:
console.log(window.innerWidth); // 800
console.log(window.innerHeight); // 600
console.log(document.documentElement.clientWidth); // 800
console.log(window.devicePixelRatio); // 1
console.log(window.scrollX, window.scrollY); // 0 0
console.log(window.pageYOffset === window.scrollY); // true
window.scrollTo({ top: 500, left: 0, behavior: "instant" });
console.log(window.scrollY); // 500
window.scrollBy(0, 100);
console.log(window.scrollY); // 600
scrollY 是倍精度浮點數,在支援次像素的裝置上不一定是整數,需要整數時可用 Math.round()。要捲動視窗用 scrollTo()、scrollBy() 這些方法,不能直接對 scrollY 指定值。
視窗尺寸改變時會觸發 resize 事件,見後面的事件一節。
框架關係:parent、top、frames
頁面裡有 <iframe> 時,每個 iframe 都有自己的 Window。下面的頁面嵌了一個 iframe(id="child"):
<iframe id="child" srcdoc="<p>子頁面</p>"></iframe>
const child = document.getElementById("child").contentWindow;
console.log(window.length); // 1
console.log(window.frames[0] === child); // true
console.log(child.parent === window); // true
console.log(child.top === window); // true
console.log(child.frameElement.id); // child
console.log(window.parent === window); // true
console.log(window.frameElement); // null
length:視窗裡的框架(<frame>或<iframe>)數量。parent:上一層視窗。MDN 說明,沒有上層時parent指向自己。top:階層最上層的視窗。frameElement:這個視窗被嵌入的元素(例如<iframe>),沒有被嵌入時是null。
常用方法
Window 的方法很多,下面是常用的。它們多半不必寫 window.,直接用名稱就能呼叫:
| 類別 | 方法 | 說明 |
|---|---|---|
| 計時 | setTimeout()、clearTimeout()、setInterval()、clearInterval() | 延遲或重複執行函式 |
| 動畫與排程 | requestAnimationFrame()、cancelAnimationFrame()、queueMicrotask() | 下次重繪前執行、排入微任務 |
| 網路 | fetch() | 發出網路請求 |
| 樣式與媒體 | getComputedStyle()、matchMedia() | 取得計算後樣式、建立媒體查詢物件 |
| 捲動 | scroll()、scrollTo()、scrollBy() | 捲動視窗 |
| 開關視窗 | open()、close()、focus()、print() | 開新視窗、關閉視窗、取得焦點、列印 |
| 跨視窗 | postMessage() | 在不同視窗之間傳遞訊息 |
| 對話框 | alert()、confirm()、prompt() | 內建的提示、確認與輸入對話框 |
| 編碼與複製 | atob()、btoa()、structuredClone() | base-64 解碼與編碼、結構化複製 |
matchMedia() 與 getComputedStyle()
matchMedia() 接收媒體查詢字串,回傳 MediaQueryList。MDN 說明,和 CSS 一樣,媒體功能(media feature)要放在括號裡,所以 "(width <= 600px)" 有效,"width <= 600px" 無效。matches 屬性是目前是否符合:
const query = window.matchMedia("(width <= 600px)");
console.log(query.media); // (width <= 600px)
console.log(query.matches); // false(視窗寬度 800 時)
getComputedStyle() 取得元素計算後的樣式:
const box = document.getElementById("box");
console.log(window.getComputedStyle(box).display); // block
計時器
setTimeout() 在指定毫秒後執行一次函式,會回傳計時器編號;用 clearTimeout() 傳入這個編號就能取消:
setTimeout(() => console.log("10 毫秒後執行"), 10);
const id = window.setTimeout(() => console.log("不會執行"), 20);
window.clearTimeout(id);
open() 與 close()
window.open(url, target, windowFeatures) 把資源載入新的或既有的瀏覽環境(分頁、視窗或 iframe)。順利開啟時回傳該視窗的 WindowProxy;被瀏覽器的彈出視窗封鎖器擋下等情況,回傳 null。MDN 提醒,現代瀏覽器的封鎖政策很嚴,彈出視窗必須直接回應使用者操作,每次呼叫 open() 都要有各自的使用者動作。
下面的範例放在按鈕的 click 處理函式裡:
document.getElementById("openBtn").addEventListener("click", () => {
const popup = window.open("about:blank", "demo");
console.log(popup !== null); // true
console.log(popup.closed); // false
console.log(popup.opener === window); // true
popup.close();
setTimeout(() => console.log(popup.closed), 100); // true
});
close() 只能關閉由腳本建立的視窗(例如 open() 開的,或用一般連結、表單開啟的)。MDN 說明,用瀏覽器介面開啟的分頁(例如 Ctrl+點擊)通常不能被腳本關閉,主控台會出現警告。對 iframe.contentWindow 呼叫 close() 沒有效果。
事件
Window 繼承 EventTarget,用 addEventListener() 監聽,也可以指定 oneventname 屬性(例如 onresize)。MDN 列出的事件包含:
| 事件 | 說明 |
|---|---|
resize | 視窗大小改變 |
error | 資源載入失敗,或腳本執行錯誤 |
languagechange | 使用者偏好的語言改變 |
storage | 其他文件修改了 localStorage 或 sessionStorage |
online、offline | 瀏覽器連上或失去網路 |
focus、blur | 視窗取得或失去焦點 |
MDN 說明,resize 事件只會在 window 上觸發,只有註冊在 window 上的處理函式收得到。想知道其他元素的尺寸變化,要改用 ResizeObserver。
window.addEventListener("resize", () => {
console.log("resize", window.innerWidth, window.innerHeight);
});
window.addEventListener("online", () => console.log("online", navigator.onLine));
window.addEventListener("offline", () => console.log("offline", navigator.onLine));
視窗調整成 500 × 400 時輸出 resize 500 400;網路中斷時輸出 offline false,恢復後輸出 online true。
已棄用的成員
MDN 把下列成員標為已棄用,新程式碼不要使用:
window.event:回傳目前正在處理的事件。MDN 建議改用事件處理函式收到的Event參數,因為window.event並非所有環境都支援,在 shadow tree 裡的事件也不準確。window.status、window.external、window.orientation。- 方法
captureEvents()、releaseEvents()、blur()。
注意事項
window只存在於瀏覽器的視窗環境:Web Worker 用self,Node.js 用global;要寫跨環境的程式碼,用globalThis。- script 頂層的
var會污染全域物件:同名的全域屬性可能互相覆蓋,用let、const或模組可以避免。 id與name會變成window的屬性:取得元素時用明確的document.getElementById()。innerWidth包含捲軸:要排除捲軸,讀document.documentElement.clientWidth。open()可能回傳null:要先檢查,再操作回傳的視窗。scrollY不一定是整數:需要整數時自行Math.round()。
支援版本
依 MDN 瀏覽器相容性資料(browser-compat-data,查詢日期 2026-11-24),各成員開始支援的版本如下:
| 成員 | Chrome/Edge | Firefox | Safari |
|---|---|---|---|
Window 介面 | 1/12 | 1 | 1 |
innerWidth | 1/12 | 1 | 3 |
matchMedia() | 9/12 | 6 | 5.1 |
其他成員的支援情況請查各自的 MDN 頁面。
補充說明:範例在 Chrome 158 執行(頁面網址
https://example.org/index.html,視口 800 × 600,無頭模式),頁面由測試程式攔截回傳。window.outerWidth等實體視窗尺寸在無頭模式下沒有意義,所以範例沒有列出數值。Node.js 22 的範例輸出與 Web Worker 的輸出分別在對應環境執行。
發佈留言