重新整理頁面看似只有一種做法,實際上寫法很多,行為卻各有差異。本文整理 JavaScript 的八種寫法、三種自動刷新方式,以及 ASP.NET 與框架環境下的跨視窗刷新。
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.replace():它會用新頁面取代目前的歷史紀錄,重新整理後按上一頁不會回到原頁,而是回到再上一頁。其餘寫法多數會保留歷史紀錄。document.execCommand 與 window.navigate 屬於較早期的 API,新專案不建議使用。
把這行放進 <head> 區域:
<meta http-equiv="refresh" content="20">
其中 20 代表每隔 20 秒重新整理一次。
<meta http-equiv="refresh" content="20;url=https://example.com/">
20 秒後跳轉到指定網址。注意這種做法對螢幕閱讀器使用者不友善,若用於實際產品應提供關閉倒數的方式。
<script language="JavaScript">
function myrefresh() {
window.location.reload();
}
setTimeout('myrefresh()', 1000); // 指定 1 秒後刷新
</script>
這裡的字串寫法 setTimeout('myrefresh()', 1000) 在現代寫法中應改為直接傳函式參照:setTimeout(myrefresh, 1000)。字串形式會經過 eval 解析,既慢也不安全。
// 寫法一
this.Response.Write("<script>opener.location.reload();</script>");
// 寫法二
this.Response.Write("<script>opener.window.location.href = opener.window.location.href;</script>");
// 寫法三
Response.Write("<script language=javascript>opener.window.navigate('你要刷新的頁.asp');</script>");
opener 指的是用 window.open() 開啟這個視窗的父視窗。子視窗執行完動作後,用它來觸發父視窗重新載入。
// 重新整理包含該框架的整個頁面
<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>
opener 可能不存在。若使用者直接開啟這個頁面而非從父視窗開啟,opener 會是 null,存取 opener.location 會拋錯。建議加上防護:
if (window.opener && !window.opener.closed) {
window.opener.location.reload();
}
onunload 已不可靠。現代瀏覽器基於效能與行動版考量,對 onunload 的觸發時機做了許多限制(行動裝置上經常根本不觸發)。若需要在頁面離開時通知伺服器,應改用 navigator.sendBeacon()。
跨域時會失敗。若父視窗與子視窗不同源,存取 opener.location 或 parent.location 都會因同源策略而失敗,此時必須改用 postMessage 溝通。