我可以使用JavaScript强制对iframe进行硬刷新吗?

jku*_*zak 9 javascript iframe refresh

我在Stack Overflow上找到了很多关于如何用JavaScript刷新iframe的答案.

例如:

他们工作正常.但是,如果最近iframe中的页面已更改,则刷新将不会显示此更改.有没有办法可以强制刷新指定的iframe,以便显示新版本?

use*_*118 10

如果iframe同源,则可以强制使用完整页面重新加载

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
Run Code Online (Sandbox Code Playgroud)

在jsFiddle上查看示例

有关Mozilla开发人员维基的更多信息


如果您可以控制为该页面发送的HTTP标头iframe,您还可以指示浏览器不要首先缓存它.
此外,大多数网页完全忽略查询字符串中没有处理代码的参数,因此您可以向查询字符串添加随机值或时间戳,以确保浏览器将其视为"新"页面而不是使用缓存副本:

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=...
}
Run Code Online (Sandbox Code Playgroud)

使用new Date().getTime()而不是Date.now()如果对旧的浏览器的支持是很重要的.


Geo*_*rge 7

使用URL重新加载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;
Run Code Online (Sandbox Code Playgroud)

如果我们能够看到您当前拥有的代码,那么为您提供解决方案会更容易.

希望它有所帮助.

  • 我正在运行相同版本的 Chrome,user2428118 提供的答案仍然适用于我。 (2认同)