「刷新頁面」看似簡單,但在不同情境下(重新載入自己、刷新父視窗、刷新框架內的其他頁)寫法差異不小。以下依場景分類整理。
1. history.go(0)
2. location.reload()
3. location = location
4. location.assign(location)
5. document.execCommand('Refresh')
6. window.navigate(location)
7. location.replace(location)
8. document.URL = location.href
實務上最常用的是 location.reload();若不想讓重新整理紀錄被寫入瀏覽器歷史,可改用 location.replace()。
把 meta 標籤放進 <head> 區即可,數字代表秒數:
<!-- 每 20 秒重新載入一次 --> <meta http-equiv="refresh" content="20"> <!-- 20 秒後跳轉到指定網址 --> <meta http-equiv="refresh" content="20;url=https://example.com/">
若偏好用 JS 控制:
<script language="JavaScript">
function myrefresh(){
window.location.reload();
}
setTimeout('myrefresh()', 1000); // 每 1 秒刷新一次
</script>
1. this.Response.Write("<script>opener.location.reload();</script>");
2. this.Response.Write("<script>opener.window.location.href = opener.window.location.href;</script>");
3. Response.Write("<script language=javascript>opener.window.navigate('你要刷新的頁.asp');</script>");
刷新包含當前框架的整個頁面:
<script language=JavaScript> parent.location.reload(); </script>
子視窗刷新開啟它的父視窗:
<script language=JavaScript> self.opener.location.reload(); </script> <!-- 或寫成連結 --> <a href="javascript:opener.location.reload()">刷新</a>
刷新另一個框架中的頁面:
<script language=JavaScript> parent.另一FrameID.location.reload(); </script>
想在開窗或關窗時觸發刷新,直接在 body 上掛事件即可:
<body onload="opener.location.reload()"> <!-- 開啟視窗時刷新 --> <body onunload="opener.location.reload()"> <!-- 關閉視窗時刷新 --> <script language="javascript"> window.opener.document.location.reload() </script>
選用建議:只需要重新取得伺服器資料時用 reload();想避免重複送出表單或清除某段歷史紀錄時,改用 replace() 會更安全。