// 打開新窗口
const win = window.open("https://example.com", "myWin", "width=600,height=400");
// 關閉窗口(僅限腳本打開的窗口)
win.close();
// 當前窗口自關閉
window.close();
| 方法 | 類型 | 說明 |
|---|---|---|
moveTo(x, y) | 絕對 | 移動窗口左上角至屏幕座標 (x, y) |
moveBy(dx, dy) | 相對 | 相對當前位置移動 (dx, dy) |
resizeTo(w, h) | 絕對 | 設置窗口外部寬高(含邊框、標題欄) |
resizeBy(dw, dh) | 相對 | 在當前尺寸基礎上調整 |
scrollTo(x, y) | 絕對 | 滾動文檔至絕對座標 |
scrollBy(dx, dy) | 相對 | 相對當前滾動位置偏移 |
限制:現代瀏覽器為防濫用,對非 window.open 打開的窗口、跨域窗口、最小化/最大化狀態下的窗口,可能忽略或限制這些方法。
function maximizeWindow() {
if (window.screen) {
const width = screen.availWidth;
const height = screen.availHeight;
window.moveTo(0, 0);
window.resizeTo(width, height);
}
}
// 按鈕綁定
// <button onclick="maximizeWindow()">最大化</button>
注意:resizeTo 設置的是整個瀏覽器窗口尺寸,非視口大小。
function openAd() {
window.open("adpage.html", "adWin", "width=468,height=80,left=0,top=0");
}
<script>
let pos = 0, inc = 5, timerId;
const aw = screen.availWidth;
const adWidth = 468;
function startAd() {
if (window.screen) {
window.moveTo(pos, 0);
timerId = setInterval(moveAd, 50);
}
}
function moveAd() {
if (pos <= 0) inc = 5;
if (pos + adWidth + 10 + 5 > aw) inc = -5; // 10 為邊框補償,5 為邊距
pos += inc;
window.moveTo(pos, 0);
}
window.onload = startAd;
// 可選:停止按鈕
// function stopAd() { clearInterval(timerId); }
</script>
同源策略禁止腳本操控不同源(協議/域名/端口不同)的窗口內容或屬性。僅能對同源窗口或自身窗口調用上述方法。
window.open 被攔截器阻擋。postMessage 實現安全跨域通信。