window 是瀏覽器物件模型 (BOM) 的頂層物件,所有全域變數、函式皆為其屬性/方法。本文整理實務常用操作。
// 基本語法
window.open(url, name, features, replace);
// 實用範例:無工具列彈出視窗
const popup = window.open(
'https://example.com',
'popupWindow',
'width=600,height=400,top=100,left=100,' +
'toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no'
);
// 取得回傳的視窗參考,可後續操作
if (popup) {
popup.focus(); // 置頂
// popup.close(); // 關閉
}
| 參數 | 說明 | 值範圍 |
|---|---|---|
| width/height | 視窗寬高 | 像素數 |
| top/left | 螢幕座標 | 像素數 |
| toolbar | 工具列 | yes/no/1/0 |
| menubar | 選單列 | yes/no |
| scrollbars | 捲軸 | yes/no |
| resizable | 可調整大小 | yes/no |
| location | 網址列 | yes/no |
| status | 狀態列 | yes/no |
注意:showModalDialog 已從 Web 標準移除,Chrome 37+、Firefox、Edge 均不支援。現代替代方案:
window.open + window.postMessage 跨視窗通訊<dialog> 原生 HTML 元素 (支援度良好)function closeWindow() {
// 標準做法:僅能關閉由 script 開啟的視窗
window.close();
}
// 若非 script 開啟 (如使用者直接輸入網址),需繞過確認:
function forceClose() {
window.opener = null; // 切斷開啟者關聯
window.open('', '_self'); // 開啟空白頁覆蓋自己
window.close(); // 關閉
}
// 框架頁面關閉頂層
function closeTopFrame() {
window.opener = null;
window.open('', '_top');
window.top.close();
}
// 重新載入目前頁面
window.location.reload(); // 快取重載
window.location.reload(true); // 強制從伺服器重載
// 跳轉新頁面
window.location.href = 'https://example.com';
window.location.assign('https://example.com'); // 同 href,有歷史紀錄
window.location.replace('https://example.com'); // 取代歷史紀錄,無法回上頁
// 取得 URL 組成部分
console.log(location.protocol); // "https:"
console.log(location.host); // "example.com:8080"
console.log(location.hostname); // "example.com"
console.log(location.port); // "8080"
console.log(location.pathname); // "/path/page.html"
console.log(location.search); // "?id=123&name=abc"
console.log(location.hash); // "#section1"
// 修改單一參數不重載
const params = new URLSearchParams(location.search);
params.set('page', '2');
history.replaceState(null, '', `${location.pathname}?${params}`);
history.back(); // 等同 history.go(-1)
history.forward(); // 等同 history.go(1)
history.go(-2); // 後退兩頁
history.go(3); // 前進三頁
// HTML5 History API (SPA 必備)
history.pushState({page: 1}, 'Title', '/page1'); // 新增歷史
history.replaceState({page: 2}, 'Title', '/page2'); // 替換當前歷史
window.onpopstate = e => {
if (e.state) console.log('回到:', e.state.page);
};
// 父視窗
const child = window.open('child.html');
child.onload = () => {
// 父 → 子
child.document.getElementById('input').value = '來自父視窗';
};
// 子視窗 (child.html)
function sendToParent() {
const val = document.getElementById('input').value;
if (window.opener && !window.opener.closed) {
window.opener.document.getElementById('parentInput').value = val;
window.close();
}
}
// 父視窗
const child = window.open('https://other-domain.com/child.html');
window.addEventListener('message', e => {
// 安全性:驗證來源
if (e.origin !== 'https://other-domain.com') return;
console.log('收到子視窗資料:', e.data);
document.getElementById('parentInput').value = e.data;
});
// 子視窗
function sendData() {
const data = {name: 'John', age: 30};
// 目標來源指定為父視窗 origin,或 '*' (不安全)
window.opener.postMessage(data, 'https://parent-domain.com');
}
// 寫入 (任一視窗)
localStorage.setItem('sharedData', JSON.stringify({token: 'abc123'}));
// 監聽 (其他同源視窗)
window.addEventListener('storage', e => {
if (e.key === 'sharedData' && e.newValue) {
console.log('資料更新:', JSON.parse(e.newValue));
}
});
| 屬性/方法 | 說明 |
|---|---|
| window.innerWidth/innerHeight | 瀏覽器視口尺寸 (含捲軸) |
| window.outerWidth/outerHeight | 整個瀏覽器視窗尺寸 |
| window.screenX/screenY | 視窗螢幕座標 |
| window.scrollX/scrollY | 捲軸位置 (同 pageXOffset/YOffset) |
| window.scrollTo(x, y) | 捲動至指定位置 |
| window.scrollBy(dx, dy) | 相對捲動 |
| window.devicePixelRatio | 螢幕像素比 (Retina 為 2) |
| window.navigator | 瀏覽器資訊物件 |
| window.localStorage/sessionStorage | Web Storage |
Window 物件是前端與瀏覽器互動的核心入口。現代開發重點:
showModalDialog,改用 <dialog> 或 SPA ModalpostMessage,嚴格驗證 originpushState/replaceState)requestAnimationFrame 或防抖節流