萬盛學電腦網

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

JavaScript 頁面重導向完整指南:location.href、replace、assign 與延遲跳轉

前言

客戶端重導向透過 `window.location` 物件實現。理解 `href`、`assign()`、`replace()` 差異對歷史記錄、SEO、用戶體驗至關重要。

三種核心方式

方式語法歷史記錄用途
location.href = url屬性指派新增記錄一般導向,用戶可「返回」
location.assign(url)方法呼叫新增記錄語意明確,可被瀏覽器攔截/記錄
location.replace(url)方法呼叫替換 當前記錄登入後導向、結果頁、避免返回迴圈

基本範例

<script>
// 立即導向
window.location.href = 'https://example.com';

// 延遲 3 秒導向並顯示訊息
function delayedRedirect(url, seconds, message) {
  document.body.innerHTML = `

${message || '正在跳轉...'} (${seconds}s)

`; setTimeout(() => location.assign(url), seconds * 1000); } // 依瀏覽器導向不同頁面 (舊技巧,現代用響應式/特性偵測) const ua = navigator.userAgent; if (/MSIE|Trident/.test(ua)) location.href = '/ie.html'; else if (/Edg/.test(ua)) location.href = '/edge.html'; else location.href = '/modern.html'; </script>

延遲跳轉最佳實踐

function countdownRedirect(url, seconds, onTick) {
  let remaining = seconds;
  const timer = setInterval(() => {
    onTick?.(remaining);
    if (--remaining < 0) {
      clearInterval(timer);
      location.replace(url); // 替換歷史,避免用戶返回倒數頁
    }
  }, 1000);
  return () => clearInterval(timer); // 回傳取消函式
}

// 使用
const cancel = countdownRedirect('/dashboard', 5, sec => {
  document.getElementById('countdown').textContent = sec;
});

// 用戶點擊取消
document.getElementById('cancelBtn').onclick = cancel;

SEO 與無障礙注意

  • 301/302 Server-side Redirect:永久/暫時移動,搜尋引擎首選,傳遞權重。
  • Meta Refresh:`` 可作為 JS 失效備援,但 W3C 不推薦。
  • 無障礙:延遲導向需提供暫停/取消機制 (WCAG 2.2.1)。

總結

一般導向用 `location.href` 或 `assign()`;不想讓用戶返回上一頁用 `replace()`。重要流程(登入、付款完成)務必採 Server-side Redirect 確保 SEO 與可靠性。

copyright © 萬盛學電腦網 all rights reserved