一、歷史導航(History API)
| 方法 | 說明 | 範例 |
history.back() | 返回上一頁 | <a href="javascript:history.back()">返回</a> |
history.forward() | 前進下一頁 | window.history.forward() |
history.go(n) | 相對跳轉,負數返回 | history.go(-2) 返回兩頁 |
history.go(url) | 跳轉至歷史記錄中的特定 URL | history.go('https://example.com') |
二、頁面跳轉(Location API)
// 1. 直接指派(會留下歷史記錄)
window.location.href = 'list.aspx';
// 2. 替換當前歷史記錄(無法返回)
window.location.replace('list.aspx');
// 3. 指派 location 物件屬性
location.assign('list.aspx'); // 同 href
location = 'list.aspx'; // 同 href
// 4. 重新載入當前頁
location.reload(); // 從伺服器重載
location.reload(true); // 強制跳過快取
三、自動重整/跳轉
1. Meta 標籤(無需 JS)
<!-- 20 秒重整一次 -->
<meta http-equiv="refresh" content="20">
<!-- 20 秒後跳轉 -->
<meta http-equiv="refresh" content="20;url=https://example.com">
2. JavaScript 定時器
// 1 秒重整一次
setInterval(function() { location.reload(); }, 1000);
// 5 秒後跳轉
setTimeout(function() { location.href = 'https://example.com'; }, 5000);
四、框架/父視窗操作
// 重新載入父視窗
parent.location.reload();
// 子視窗重新載入父視窗
opener.location.reload();
// 或 刷新父頁
// 重新載入特定 iframe
parent.frames['frameName'].location.reload();
// 或
document.getElementById('myIframe').contentWindow.location.reload();
五、ASP.NET 伺服器端輸出重整腳本
// 1. 重整父視窗
Response.Write("");
// 2. 重新導向父視窗
Response.Write("");
// 3. 關閉視窗時重整父視窗
// 前端 body:
六、小技巧:動態載入 JS(防重複)
if (typeof SWFObject === 'undefined') {
document.write('<\/script>');
}
總結建議
- 單頁應用(SPA)請使用
history.pushState/replaceState 配合路由庫,避免整頁重載。
- 重整操作優先用
location.reload(),語意最清晰。
- 跨域 iframe 無法直接操作
location,需用 postMessage 通訊。