DIV CSS 佈局教程網

JavaScript 刷新 iframe 的各種寫法與跨頁整合技巧
編輯:JavaScript綜合知識     

iframe 的刷新看起來簡單,實際寫起來卻有 name、id、跨域、雙層 iframe 等多種情境,語法也各不相同。這篇把常見做法整理成一份清單。

先以下面這個 iframe 為例:

<iframe src="1.htm" name="ifrmname" id="ifrmid"></iframe>

方法一:用 name 屬性定位

<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()">

方法二:用 id 屬性定位

<input type="button" name="Button" value="Button"
       onclick="ifrmid.window.location.reload()">

方法三:跨域情境

當 iframe 的 src 指向其他網站時,基於同源政策無法直接操作其內部 document,只能重新載入:

<input type="button" name="Button" value="Button"
       onclick="window.open(document.all.ifrmname.src, 'ifrmname', '')">

雙層 iframe:只刷新其中一層

典型場景:父頁面有兩個 iframe,左邊是連結列表,右邊是內容。內容新增後,左邊列表需要更新,但右邊不該被影響。

直覺做法是在內容 iframe 的提交後呼叫 parent.location.reload(),但這會把整個父頁面刷新,而右邊 iframe 若沒有預設 url,就會變成空白。

正確作法是針對特定 iframe 重新指定位置:

window.parent.frames["列表iframe名字"].location = "列表url";

這樣只刷新列表 iframe,內容 iframe 自己提交後的狀態不受影響。也可以用更精簡的寫法:

document.frames("refreshAlarm").location.reload(true);
document.frames("refreshAlarm").document.location.reload(true);
document.frames("refreshAlarm").document.location = "https://www.example.com/";
document.frames("refreshAlarm").src = "https://www.example.com/";

關鍵區別:iframe 標籤 vs iframe 內容

這是最容易搞混的一點:

  • document.all.refreshAlarm 或 document.frames("refreshAlarm") 取得的是那個 iframe 標籤本身,所以對它的 src 屬性操作才有效。
  • document.frames("refreshAlarm").document 取得的是iframe 裡面的文件,也就是 src 載入後的內容。

混淆這兩者,就會出現「明明寫了卻沒反應」或「改錯對象」的狀況。

附錄:頁面自動刷新的幾種方式

meta refresh(間隔 10 秒)

<meta http-equiv="refresh" content="10;url=需要刷新的頁面URL" />

setTimeout 定時刷新(2 秒)

<script language="javascript">
setTimeout("location.href='url'", 2000);
</script>

直接重新載入

<script language="javascript">
window.location.reload(true);
// 若要刷新 iframe,把 window 換成該 iframe 的 name 或 id
</script>

用 navigate(舊 IE 專用)

<script language="javascript">
window.navigate("本頁面url");
</script>

用 href 觸發重載並定時輪詢

function abc() {
    window.location.href = "/blog/window.location.href";
    setTimeout("abc()", 10000);
}

刷新框架頁的特定區塊

<script language="javascript">
top.leftFrm.location.reload();
parent.frmTop.location.reload();
</script>

現代建議

這份清單中的 document.all、window.navigate、document.frames() 都屬於舊 IE 時代的 API,window.navigate 更是早已被移除。目前跨瀏覽器的標準寫法是:

// 取得 iframe 元素
const frame = document.getElementById('ifrmid');
// 重新載入其內容(同源時可用 contentWindow)
frame.contentWindow.location.reload();
// 或直接重設 src
frame.src = frame.src;

至於跨域 iframe,同源政策下唯一可行的就是重設 src 觸發重新載入,這點至今沒變。若只是為了「資料更新後局部刷新」,現在更合理的架構是用 Ajax 局部更新 DOM,或改用 <iframe> 的 srcdoc 屬性與 postMessage 溝通,完全避開整頁刷新的成本。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved