頁面裡嵌了 iframe,卻需要從外層或另一個 iframe 去刷新它,這件事的寫法比想像中多,而且會不會成功往往取決於是否跨域。以下以一個簡單的 iframe 為例:
<iframe src="1.htm" name="ifrmname" id="ifrmid"></iframe>
<input type="button" name="Button" value="Button" onclick="document.frames('ifrmname').location.reload()">
或者
<input type="button" name="Button" value="Button" onclick="document.all.ifrmname.document.location.reload()">
<input type="button" name="Button" value="Button" onclick="ifrmid.window.location.reload()">
<input type="button" name="Button" value="Button" onclick="window.open(document.all.ifrmname.src,'ifrmname','')">
這裡有個重要觀念:同源政策會禁止外層讀寫跨域 iframe 內部的 document,所以任何試圖存取內部內容的刷新都會失敗。可行的替代方案是改寫 iframe 的 src(這屬於外層自己的屬性,不受限制),或以 window.open 重新開啟;若 iframe 內容與你同域,則可請對方透過 postMessage 通知外層。
常見結構是左側 iframe 放連結列表、右側 iframe 顯示內容。新增資料後若只想刷新列表而不影響內容,用 parent.location.reload() 會把整頁一起刷新,並非理想做法。此時可以指定目標:
window.parent.frames["列表iframe名字"].location="列表url";
另外幾種常見寫法:
document.frames("refreshAlarm").location.reload(true); document.frames("refreshAlarm").document.location.reload(true); document.frames("refreshAlarm").document.location="https://www.jb51.net/"; document.frames("refreshAlarm").src="https://www.jb51.net/";
關鍵區別在於:document.all.refreshAlarm 或 document.frames("refreshAlarm") 取得的是 iframe 標籤本身,因此對 src 的操作有效;加上 .document 之後取的才是 iframe 內部的文件內容。
若只是要讓頁面定期重載,最省事的是 meta 重新整理,放在 head 中即可:
<meta http-equiv="refresh"content="10;url=跳轉的頁面或者是需要刷新的頁面URL地址">
或用 setTimeout 控制:
<script language="javascript"> setTimeout("location.href='url'",2000);//url是要刷新的頁面URL地址 </script>
立即刷新則是:
<script language="javascript"> window.location.reload(true); //如需刷新iframe,則只需把window替換為響應的iframe的name屬性值或ID屬性值 </script>
刷新框架頁時,可用 top 與 parent 明確指定層級:
<script language="javascript"> top.leftFrm.location.reload(); parent.frmTop.location.reload(); </script>
document.all 與 document.frames(name) 都是 legacy 寫法,今日請統一改用 document.getElementById('ifrmid').contentWindow 來取得視窗物件,再操作其 location.reload()。meta refresh 雖然方便,但對螢幕閱讀器使用者不友善,也不利於返回上一頁;有條件的話,用 JS 做局部內容更新(例如 fetch 後替換 DOM)會比整框重載更流暢。