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


当前回答

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

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

其他回答

由于同源策略,当修改指向不同域的iframe时,这将不起作用。如果你的目标浏览器更新,可以考虑使用HTML5的跨文档消息传递功能。您可以在这里查看支持此功能的浏览器:http://caniuse.com/#feat=x-doc-messaging。

如果你不能使用HTML5的功能,那么你可以遵循这里列出的技巧:http://softwareas.com/cross-domain-communication-with-iframes。该博客条目也很好地定义了问题。

window.frames['frameNameOrIndex'].location.reload();
document.getElementById('iframeid').src = document.getElementById('iframeid').src

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

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

出于调试目的,可以打开控制台,将执行上下文更改为他想要刷新的帧,然后执行document.location.reload()

document.getElementById('some_frame_id').contentWindow.location.reload();

注意,在Firefox中,window.frames[]不能通过id索引,而是通过名称或索引