先準備一個 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()">
當 iframe 的 src 指向其他網站(跨域操作)時:
<input type="button" name="Button" value="Button" onclick="window.open(document.all.ifrmname.src,'ifrmname','')">
三個方案的差別在於「定位方式」與「能否跨域」。方案一、二都是同源情境下的做法,差別只是一個用 name、一個用 id;但要注意 document.frames 與 document.all 都屬於舊式 IE 語法,在現代瀏覽器中建議改用標準寫法:document.getElementById('ifrmid').contentWindow.location.reload()。
跨域之所以麻煩,是因為瀏覽器的同源政策會阻擋父頁讀取子頁的 document,reload() 自然無從呼叫。終極方案繞過的方式是「用 window.open 重新開一次同一個 src」,效果上看起來像刷新,但本質上是另開視窗。若真要跨域刷新,正確做法有兩條:一是直接重設 iframe 的 src(src 的設定不受同源政策限制,只是讀取被禁止),可視情況在網址後串時間戳避免快取;二是改用 postMessage 通知子頁自行處理。