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