我想重新加载一个<iframe>使用JavaScript。到目前为止,我发现最好的方法是将iframe的src属性设置为自身,但这不是很干净。什么好主意吗?
当前回答
现在让这个工作在chrome 66,试试这个:
const reloadIframe = (iframeId) => {
const el = document.getElementById(iframeId)
const src = el.src
el.src = ''
setTimeout(() => {
el.src = src
})
}
其他回答
document.getElementById('iframeid').src = document.getElementById('iframeid').src
它将重新加载iframe,甚至跨域! 通过IE7/8, Firefox和Chrome测试。
注意:正如@user85461所提到的,如果iframe src URL中有一个散列,这种方法就不起作用了(例如http://example.com/#something)。
如果你使用Jquery,那么有一行代码。
$('#iframeID',window.parent.document).attr('src',$('#iframeID',window.parent.document).attr('src'));
如果你们是和同一个家长一起工作的话
$('#iframeID',parent.document).attr('src',$('#iframeID',parent.document).attr('src'));
对yajra帖子的改进…我喜欢这个想法,但讨厌浏览器检测的想法。
我更倾向于ppk的观点,使用对象检测而不是浏览器检测, (http://www.quirksmode.org/js/support.html), 因为这样你实际上是在测试浏览器的能力,并据此进行操作,而不是你当时认为浏览器的能力。也不需要那么多丑陋的浏览器ID字符串解析,并且不排除您完全不了解的功能完美的浏览器。
不需要看导航器。AppName,为什么不这样做呢,测试你使用的元素呢?(如果你想要更花哨,你可以使用try{}块,但这对我来说很有效。)
function reload_message_frame() {
var frame_id = 'live_message_frame';
if(window.document.getElementById(frame_id).location ) {
window.document.getElementById(frame_id).location.reload(true);
} else if (window.document.getElementById(frame_id).contentWindow.location ) {
window.document.getElementById(frame_id).contentWindow.location.reload(true);
} else if (window.document.getElementById(frame_id).src){
window.document.getElementById(frame_id).src = window.document.getElementById(frame_id).src;
} else {
// fail condition, respond as appropriate, or do nothing
alert("Sorry, unable to reload that frame!");
}
}
这样,您可以根据自己的喜好或需要尝试尽可能多的不同排列,而不会导致javascript错误,并在所有其他方法都失败时执行一些合理的操作。在使用对象之前,对它们进行测试需要做更多的工作,但是,在我看来,这有助于编写更好、更安全的代码。
为我在IE8、Firefox(15.0.1)、Chrome (21.0.1180.89 m)和Windows上的Opera (12.0.2 m)工作过。
也许我可以通过实际测试重载函数做得更好,但这对我来说已经足够了。:)
现在让这个工作在chrome 66,试试这个:
const reloadIframe = (iframeId) => {
const el = document.getElementById(iframeId)
const src = el.src
el.src = ''
setTimeout(() => {
el.src = src
})
}
我有一个问题,因为我没有使用超时给页面时间更新,我将src设置为“,然后将其设置回原来的url,但什么都没有发生:
function reload() {
document.getElementById('iframe').src = '';
document.getElementById('iframe').src = url;
}
但是它没有重新加载网站,因为它是单线程的,第一个改变不做任何事情,因为这个函数仍然占用线程,然后它设置回原来的url,我猜chrome不重新加载是因为性能或其他什么,所以你需要做:
function setBack() {
document.getElementById('iframe').src = url;
}
function reload() {
document.getElementById('iframe').src = '';
setTimeout(setBack,100);
}
如果setTimeout时间太短,它不工作,所以如果它不工作,尝试将它设置为500或其他东西,看看它是否工作。
这是在最新版本的chrome在写这篇文章的时候。