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


当前回答

将空字符串附加到iFrame的src属性也会自动重新加载它。

document.getElementById('id').src += '';

其他回答

另一个解决方案。

const frame = document.getElementById("my-iframe");

frame.parentNode.replaceChild(frame.cloneNode(), frame);
window.frames['frameNameOrIndex'].location.reload();

从Iframe内部重新加载

如果你的应用程序在Iframe中,你可以通过替换位置href来刷新它:

document.location.href = document.location.href

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

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

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

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