2012-11-20 37 views
4

我在堆棧溢出中找到了很多關於如何用JavaScript刷新iframe的答案。我可以用JavaScript強制刷新iframe嗎?

例如:

它們工作得很好。但是,如果iframe中的頁面最近發生更改,刷新將不會顯示此更改。有什麼辦法可以強制刷新指定的iframe,以便顯示新版本?

+0

我回答類似的問題在這裏:https://stackoverflow.com/questions/2064850/how-to-refresh-an-iframe-using-javascript/47395136#47395136好運 –

回答

7

如果iframesame-origin,您可以強制重新加載整個頁面使用

iframe.contentWindow.location.reload(true);//The argument "true" will force all loaded resources, such as images, to be re-checked for expiry at the server 

View an example at jsFiddle

More information at the Mozilla Developer wiki


如果你有控制權的 iframe的頁面發送的HTTP報頭,你也可以 instruct the browser not to cache it in the first place
此外,大多數網頁完全忽略了 query string中沒有處理代碼的參數,因此您可以向查詢字符串添加一個隨機值或時間戳,以確保瀏覽器將其視爲「新」頁面,而不是使用緩存的副本:

if(iframe.src.indexOf('timestamp') > -1){ // Check if we still have a timestamp in the URL from a previous refresh 
    iframe.src = iframe.src.replace(/timestamp=[^&]+/, 'timestamp=' + Date.now()); // And if so, replace it instead of appending so the URL doesn't grow too long. 
}else{ // Else we will append the timestamp 
    iframe.src += (iframe.src.indexOf('?') > -1 ? "&" : "?") + 'timestamp=' + Date.now();// If the URL contains a ?, append &timestamp=...; otherwise, append ?timestamp=... 
} 

使用new Date().getTime()而不是Date.now()如果support for older browsers是很重要的。

+0

由於某種原因,我無法在我的網站上獲得此功能。這是我創建的測試頁面。它甚至不會刷新iframe。我添加了一些CSS3動畫,以便更輕鬆地查看頁面何時重新加載。 http://iavi.com/demo/signature/iframe.html – jkupczak

+0

JavaScript應在相關元素創建後執行。您正試圖訪問尚不存在的DOM節點。嘗試在元素後面放置'

6

重新加載的iFrame與一個網址,但給它一個唯一的ID ...

var rand = Math.floor((Math.random()*1000000)+1); 
var iframe = document.getElementById('youriframe'); 
iframe.src = "http://www.yourpage.com/yourpage.html?uid="+rand; 

它會更容易給你一個解決方案,如果我們可以看到您當前擁有的代碼。

希望它有幫助。

+0

這是唯一正確的針對Chrome 35.0.1916.114的SO回答。 – Den

+0

我使用的是Chrome的相同版本,user2428118提供的答案仍適用於我。 – jkupczak

-3
Try this code: 
<script> 
var iframe = document.getElementById('myframe'); 
iframe.src = "http://www.w3schools.com?ignore="+Math.floor(Math.random() * 1000); 
</script> 
+0

請編輯更多的信息。代碼只和「試試這個」答案都望而卻步,因爲它們不包含搜索的內容,並沒有解釋爲什麼有人要「試試這個」。 – abarisone