JavaScript 提供多種方式操作瀏覽器歷史記錄,實現頁面前進、後退或跳轉至特定記錄點。
history.go(-1):返回上一頁;history.go(-2) 返回前兩頁。history.back():等同於 history.go(-1)。window.history.forward():前進至下一頁。window.history.go(index 或 URL):跳轉至指定歷史索引或曾訪問過的 URL。<a href="javascript:history.go(-1);">返回上一頁</a>
<script>
if(!confirm('任務完成?')) { history.back(); }
</script>
onclick="window.location.href='list.aspx'" // 頁面跳轉
利用 document.write 動態注入 script 標籤,實現按需載入:
<script type="text/javascript">
if (typeof SWFObject == "undefined") {
document.write('<scr' + 'ipt type="text/javascript" src="/scripts/swfobject-1.5.js"></scr' + 'ipt>');
}
</script>
| 方法 | 說明 |
|---|---|
history.go(0) | 重新載入當前頁面 |
location.reload() | 標準刷新,可帶參數 true 強制從伺服器獲取 |
location = location | 重新賦值觸發刷新 |
location.assign(location) | 載入新文檔 |
document.execCommand('Refresh') | IE 專用 |
window.navigate(location) | IE 專用 |
location.replace(location) | 替換當前歷史記錄並刷新 |
document.URL = location.href | 修改 URL 觸發刷新 |
<meta http-equiv="refresh" content="20"> // 20 秒自動刷新
<meta http-equiv="refresh" content="20;url=https://example.com"> // 20 秒後跳轉
<script>
function myRefresh() { window.location.reload(); }
setTimeout('myRefresh()', 1000); // 每秒刷新一次
</script>
// 刷新父視窗
Response.Write("<script>opener.location.reload();</script>");
// 或指定 URL
Response.Write("<script>opener.window.location.href = opener.window.location.href;</script>");
// 使用 navigate (IE)
Response.Write("<script>opener.window.navigate('target.aspx');</script>");
// 刷新包含框架的父頁面
parent.location.reload();
// 子視窗刷新開啟它的父視窗
self.opener.location.reload();
// 或超連結方式
<a href="javascript:opener.location.reload()">刷新父頁</a>
// 刷新同級另一框架
parent.另一FrameID.location.reload();
<body onload="opener.location.reload()"> <!-- 開啟時刷新 -->
<body onUnload="opener.location.reload()"> <!-- 關閉時刷新 -->
<script>window.opener.document.location.reload()</script>