萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript Window 物件完整操作指南:開窗、關窗、跨視窗通訊、導航控制

Window 物件概覽

window 是瀏覽器物件模型 (BOM) 的頂層物件,所有全域變數、函式皆為其屬性/方法。本文整理實務常用操作。

1. 開啟新視窗

// 基本語法
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(); // 關閉
}

features 參數速查表

參數說明值範圍
width/height視窗寬高像素數
top/left螢幕座標像素數
toolbar工具列yes/no/1/0
menubar選單列yes/no
scrollbars捲軸yes/no
resizable可調整大小yes/no
location網址列yes/no
status狀態列yes/no

2. 模態對話框 (showModalDialog) - 已棄用

注意:showModalDialog 已從 Web 標準移除,Chrome 37+、Firefox、Edge 均不支援。現代替代方案:

  • 使用 window.open + window.postMessage 跨視窗通訊
  • 單頁應用 (SPA) 內部用 Modal 元件 (Bootstrap Modal, SweetAlert2, 自訂 Dialog)
  • <dialog> 原生 HTML 元素 (支援度良好)

3. 關閉視窗不跳確認框

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();
}

4. Location 物件:頁面導航與重載

// 重新載入目前頁面
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}`);

5. History 物件:前進後退

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);
};

6. 跨視窗資料傳遞

方案 A:window.open 回傳參考 (同源)

// 父視窗
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();
  }
}

方案 B:postMessage (跨域安全)

// 父視窗
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');
}

方案 C:LocalStorage/SessionStorage + storage 事件

// 寫入 (任一視窗)
localStorage.setItem('sharedData', JSON.stringify({token: 'abc123'}));

// 監聽 (其他同源視窗)
window.addEventListener('storage', e => {
  if (e.key === 'sharedData' && e.newValue) {
    console.log('資料更新:', JSON.parse(e.newValue));
  }
});

7. 常用屬性速查

屬性/方法說明
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/sessionStorageWeb Storage

總結

Window 物件是前端與瀏覽器互動的核心入口。現代開發重點:

  1. 棄用 showModalDialog,改用 <dialog> 或 SPA Modal
  2. 跨視窗通訊首選 postMessage,嚴格驗證 origin
  3. SPA 路由使用 History API (pushState/replaceState)
  4. 視窗尺寸/捲動事件請搭配 requestAnimationFrame 或防抖節流
copyright © 萬盛學電腦網 all rights reserved