我在堆棧溢出中找到了很多關於如何用JavaScript刷新iframe的答案。我可以用JavaScript強制刷新iframe嗎?
例如:
它們工作得很好。但是,如果iframe中的頁面最近發生更改,刷新將不會顯示此更改。有什麼辦法可以強制刷新指定的iframe,以便顯示新版本?
我在堆棧溢出中找到了很多關於如何用JavaScript刷新iframe的答案。我可以用JavaScript強制刷新iframe嗎?
例如:
它們工作得很好。但是,如果iframe中的頁面最近發生更改,刷新將不會顯示此更改。有什麼辦法可以強制刷新指定的iframe,以便顯示新版本?
如果iframe
是same-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
↪More information at the Mozilla Developer wiki
iframe
的頁面發送的HTTP報頭,你也可以
instruct the browser not to cache it in the first place。
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 ×tamp=...; otherwise, append ?timestamp=...
}
使用new Date().getTime()
而不是Date.now()
如果support for older browsers是很重要的。
由於某種原因,我無法在我的網站上獲得此功能。這是我創建的測試頁面。它甚至不會刷新iframe。我添加了一些CSS3動畫,以便更輕鬆地查看頁面何時重新加載。 http://iavi.com/demo/signature/iframe.html – jkupczak
JavaScript應在相關元素創建後執行。您正試圖訪問尚不存在的DOM節點。嘗試在元素後面放置'
重新加載的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;
它會更容易給你一個解決方案,如果我們可以看到您當前擁有的代碼。
希望它有幫助。
Try this code:
<script>
var iframe = document.getElementById('myframe');
iframe.src = "http://www.w3schools.com?ignore="+Math.floor(Math.random() * 1000);
</script>
請編輯更多的信息。代碼只和「試試這個」答案都望而卻步,因爲它們不包含搜索的內容,並沒有解釋爲什麼有人要「試試這個」。 – abarisone
我回答類似的問題在這裏:https://stackoverflow.com/questions/2064850/how-to-refresh-an-iframe-using-javascript/47395136#47395136好運 –