【问题标题】:Can I force a hard refresh on an iframe with JavaScript?我可以使用 JavaScript 在 iframe 上强制刷新吗?
【发布时间】:2012-11-08 18:30:08
【问题描述】:

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

例如:

他们工作得很好。但是,如果 iframe 中的页面最近发生了更改,则刷新不会显示此更改。有什么办法可以强制对指定的 iframe 进行硬刷新以显示新版本?

【问题讨论】:

标签: javascript iframe refresh


【解决方案1】:

如果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=...
}

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

【讨论】:

  • 由于某种原因,我无法在我的网站上使用它。这是我创建的测试页面。它甚至根本不刷新 iframe。我添加了一些 CSS3 动画,以便更容易看到页面何时重新加载。 iavi.com/demo/signature/iframe.html
  • JavaScript 应该在相关元素创建后执行。您正在尝试访问尚不存在的 DOM 节点。尝试将<script> 放在元素之后。
  • 我先是这样,但它对我不起作用。把它改回来,它现在可以工作了。我一定搞砸了别的东西。现在很好用,谢谢!
  • 简单的解决方案,适用于我的 Chrome 版本 63.0
  • 如果您希望 IE 刷新 IFrame 上的图像,这是必要的。谢谢。
【解决方案2】:

使用 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;

如果我们能看到您当前拥有的代码,就更容易为您提供解决方案。

希望对您有所帮助。

【讨论】:

  • 这是 Chrome 35.0.1916.114 SO 上唯一正确的答案。
  • 我正在运行相同版本的 Chrome 并且 user2428118 提供的答案仍然适用于我。
【解决方案3】:

我为此苦苦挣扎了很久。如果您的 iframe 与您的网页位于同一域中,则上述许多方法都有效。

但是,如果您的 iframe 来自其他域,则这些方法不起作用(由于 CORS 政策)。

更改 src 属性类型可行,但不会导致 iframe 正确重绘。如果您使用 iframe 在页面中嵌入 Google 地图,这一点尤其明显。

我最终发现你需要:

1) 保存iframe的source属性

2) 从 DOM 中移除 iframe

3) 在步骤 1 中保存的源属性末尾添加一个随机查询参数。

4) 将 iframe 添加回 DOM(具有唯一源属性)。

 //save the source of the iframe minus the unique identifier
    tempElementSrc = $('#the-iframe').attr('src').substring(0,$('#the-iframe').attr('src').lastIndexOf('&', $('#the-iframe').attr('src')));

  //remove the iframe
    $('#the-iframe').remove();

  //readd the iframe with the new source including random query string
  $('#container-id').append('<iframe width=\"100%\" id=\"iframe-id\" src=\"' + tempElementSrc + '&' + Date.now() + '\">');

【讨论】:

    猜你喜欢
    • 2012-02-25
    • 1970-01-01
    • 2010-11-17
    • 2015-04-10
    • 2011-07-09
    • 2016-02-22
    • 2013-10-24
    • 2011-10-20
    • 2012-11-01
    相关资源
    最近更新 更多