我想重新加载一个<iframe>使用JavaScript。到目前为止,我发现最好的方法是将iframe的src属性设置为自身,但这不是很干净。什么好主意吗?


当前回答

window.frames['frameNameOrIndex'].location.reload();

其他回答

<script type="text/javascript">
  top.frames['DetailFrame'].location = top.frames['DetailFrame'].location;
</script> 

在我的例子中,简单地替换iframe元素的src属性并不能令人满意,因为在加载新页面之前,人们会看到旧的内容。如果你想提供即时的视觉反馈,这种方法会更好:

var url = iframeEl.src;
iframeEl.src = 'about:blank';
setTimeout(function() {
    iframeEl.src = url;
}, 10);

现在让这个工作在chrome 66,试试这个:

const reloadIframe = (iframeId) => {
    const el = document.getElementById(iframeId)
    const src = el.src
    el.src = ''
    setTimeout(() => {
        el.src = src
    })
}

新url

location.assign("http:google.com");

assign()方法加载一个新文档。

重新加载

location.reload();

reload()方法用于重新加载当前文档。

document.getElementById('iframeid').src = document.getElementById('iframeid').src

它将重新加载iframe,甚至跨域! 通过IE7/8, Firefox和Chrome测试。

注意:正如@user85461所提到的,如果iframe src URL中有一个散列,这种方法就不起作用了(例如http://example.com/#something)。