萬盛學電腦網

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

JavaScript 定時自動跳轉與關閉視窗完整實作指南

核心 API:setTimeout / setInterval

// 一次性延遲執行
var timerId = setTimeout(function() {
  // 延遲後執行的代碼
}, delayMs); // delayMs: 毫秒

// 週期性執行
var intervalId = setInterval(function() {
  // 每隔 delayMs 執行一次
}, delayMs);

// 清除定時器
clearTimeout(timerId);
clearInterval(intervalId);

一、延遲跳轉頁面

基本實作

// 3 秒後跳轉至指定頁面
setTimeout(function() {
  window.location.href = "https://www.example.com";
}, 3000);

// 可攜帶參數
var targetUrl = "success.html?orderId=" + orderId;
setTimeout(function() {
  location.href = targetUrl;
}, 2000);

倒數計時顯示 + 跳轉

function countdownRedirect(url, seconds, selector) {
  var $el = $(selector);
  var remaining = seconds;
  
  $el.text("剩餘 " + remaining + " 秒後自動跳轉...");
  
  var timer = setInterval(function() {
    remaining--;
    if (remaining > 0) {
      $el.text("剩餘 " + remaining + " 秒後自動跳轉...");
    } else {
      clearInterval(timer);
      $el.text("正在跳轉...");
      window.location.href = url;
    }
  }, 1000);
  
  // 使用者點擊取消
  $("#cancelBtn").one("click", function() {
    clearInterval(timer);
    $el.text("已取消自動跳轉");
  });
}

// 使用
countdownRedirect("/dashboard", 10, "#countdown");

完整可執行範例

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>延遲跳轉示範</title>
  <style>
    .container { max-width: 500px; margin: 50px auto; padding: 30px; text-align: center; }
    .countdown { font-size: 24px; color: #dc3545; font-weight: bold; margin: 20px 0; }
    .btn { padding: 10px 24px; margin: 5px; border: none; border-radius: 4px; cursor: pointer; }
    .btn-secondary { background: #6c757d; color: white; }
    .btn-primary { background: #007bff; color: white; }
  </style>
</head>
<body>
  <div class="container">
    <h2>操作成功</h2>
    <p>訂單已建立,系統將自動跳轉至訂單頁面</p>
    <div class="countdown" id="countdown">剩餘 5 秒後跳轉...</div>
    <button class="btn btn-secondary" id="cancelBtn">取消跳轉</button>
    <button class="btn btn-primary" id="gotoBtn">立即前往</button>
  </div>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    var TARGET_URL = "/order/detail/12345";
    var SECONDS = 5;
    var timer = null;
    
    function startCountdown() {
      var remaining = SECONDS;
      $("#countdown").text("剩餘 " + remaining + " 秒後跳轉...");
      
      timer = setInterval(function() {
        remaining--;
        if (remaining > 0) {
          $("#countdown").text("剩餘 " + remaining + " 秒後跳轉...");
        } else {
          clearInterval(timer);
          doRedirect();
        }
      }, 1000);
    }
    
    function doRedirect() {
      $("#countdown").text("正在跳轉...");
      window.location.href = TARGET_URL;
    }
    
    $("#cancelBtn").click(function() {
      if (timer) { clearInterval(timer); timer = null; }
      $("#countdown").text("已取消自動跳轉").css("color", "#6c757d");
      $(this).prop("disabled", true);
    });
    
    $("#gotoBtn").click(doRedirect);
    
    startCountdown();
  </script>
</body>
</html>

二、延遲關閉視窗

基本實作

// 1 秒後關閉當前視窗
setTimeout(function() {
  window.close();
}, 1000);

// 綁定按鈕
$("#closeBtn").click(function() {
  setTimeout(window.close, 1000);
});

瀏覽器限制與相容性

瀏覽器window.close() 行為備註
Chrome僅允許關閉由 window.open() 開啟的視窗使用者手動開啟的分頁無法關閉
Firefox同 Chrome,嚴格限制需 dom.allow_scripts_to_close_windows = true
Edge同 ChromeChromium 內核相同行為
IE (舊版)允許關閉任何視窗 (會提示確認)已淘汰
Safari嚴格限制需使用者互動觸發

跨瀏覽器相容關閉函式

function closeWindow() {
  // 嘗試標準關閉
  window.close();
  
  // 如果失敗 (非 window.open 開啟),嘗試繞過 (僅舊瀏覽器有效)
  // 現代瀏覽器無法繞過,建議改為導向關閉頁面
  if (!window.closed) {
    // 方案 A:導向關閉提示頁
    window.location.href = "/window-closed.html";
    
    // 方案 B:自我導向 about:blank (部分瀏覽器允許)
    // window.location.href = "about:blank";
    
    // 方案 C:開啟空白頁再關閉 (舊技巧,現代瀏覽器多失效)
    // var w = window.open("", "_self"); w.close();
  }
}

// 延遲關閉
function delayedClose(ms) {
  setTimeout(closeWindow, ms || 1000);
}

三、進階場景:彈出視窗自動關閉並通知父頁面

子視窗 (popup.html)

<script>
function notifyParentAndClose(data, delayMs) {
  setTimeout(function() {
    // 1. 通知父視窗 (同源策略允許)
    if (window.opener && !window.opener.closed) {
      try {
        // 呼叫父視窗函式
        if (typeof window.opener.onChildClosed === "function") {
          window.opener.onChildClosed(data);
        }
        // 或觸發自訂事件
        window.opener.dispatchEvent(new CustomEvent("childClosed", { detail: data }));
      } catch (e) {
        console.warn("無法通知父視窗:", e);
      }
    }
    
    // 2. 關閉自己
    window.close();
  }, delayMs || 1000);
}

// 使用:支付完成後 2 秒關閉
notifyParentAndClose({ orderId: "12345", status: "paid" }, 2000);
</script>

父視窗 (parent.html)

<script>
function openPaymentWindow() {
  var popup = window.open("/payment.html?order=123", "paymentWin", "width=500,height=600");
  
  // 定義回呼
  window.onChildClosed = function(data) {
    console.log("子視窗關閉,收到資料:", data);
    if (data.status === "paid") {
      loadOrderDetail(data.orderId);
      showSuccess("付款成功!");
    }
  };
  
  // 也可用事件監聽
  window.addEventListener("childClosed", function(e) {
    console.log("事件收到:", e.detail);
  });
  
  // 監控子視窗狀態 (輪詢備援)
  var checkClosed = setInterval(function() {
    if (popup.closed) {
      clearInterval(checkClosed);
      console.log("偵測到子視窗已關閉 (輪詢)");
    }
  }, 500);
}
</script>

四、單頁應用 (SPA) 路由導向替代方案

現代 SPA 不使用 `window.location.href` 跳轉,改用路由器:

Vue Router

// 延遲導向
setTimeout(() => {
  this.$router.push({ path: '/success', query: { orderId: this.orderId } });
}, 2000);

// 或使用 beforeRouteLeave 守衛確認

React Router

import { useNavigate } from 'react-router-dom';

function SuccessPage() {
  const navigate = useNavigate();
  
  useEffect(() => {
    const timer = setTimeout(() => {
      navigate('/dashboard', { replace: true }); // replace: 不保留歷史
    }, 3000);
    return () => clearTimeout(timer);
  }, [navigate]);
  
  return 
3秒後自動跳轉...
; }

五、最佳實踐總結

  1. 跳轉優先用 location.href,需不保留歷史用 location.replace()
  2. 倒數計時顯示 提升使用者體驗,提供「取消」與「立即前往」選項
  3. window.close() 受瀏覽器嚴格限制,僅適用 window.open() 開啟的視窗;一般頁面改用導向關閉提示頁
  4. 彈出視窗通知父頁面 使用 window.opener 或 CustomEvent,注意同源策略
  5. SPA 專案 使用路由器 API 而非直接操作 location
  6. 清理定時器:組件銷毀/頁面卸載時 clearTimeout/clearInterval 防止記憶體洩漏

總結

JavaScript 定時跳轉使用 setTimeout(() => location.href = url, ms),定時關閉視窗使用 setTimeout(window.close, ms) 但受瀏覽器嚴格限制。實務開發應提供倒數計時 UI、取消選項、立即跳轉按鈕。彈出視窗場景需配合 window.opener 實現父子通訊。SPA 專案請使用框架路由器 API。現代瀏覽器環境下,無法強制關閉使用者主動開啟的分頁,這是安全機制設計使然。

copyright © 萬盛學電腦網 all rights reserved