如何使用 Javascript 刷新 IFrame?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2064850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to refresh an IFrame using Javascript?
提问by Elitmiar
I have a webpage with an IFrame and a Button, once the button is pressed I need the IFrame to be refreshed. Is this possible, if so how? I searched and could not find any answers.
我有一个带有 IFrame 和一个按钮的网页,一旦按下按钮,我需要刷新 IFrame。这是可能的,如果可以,如何?我搜索并找不到任何答案。
回答by kjagiello
var iframe = document.getElementById('youriframe');
iframe.src = iframe.src;
回答by nfechner
This should help:
这应该有帮助:
document.getElementById('FrameID').contentWindow.location.reload(true);
EDIT: Fixed the object name as per @Joro's comment.
编辑:根据@Joro 的评论修正了对象名称。
回答by Horia Dragomir
provided the iframe is loaded from the same domain, you can do this, which makes a little more sense:
如果 iframe 是从同一个域加载的,你可以这样做,这更有意义:
iframe.contentWindow.location.reload();
回答by Marek Pavelek
Works for IE, Mozzila, Chrome
适用于 IE、Mozzila、Chrome
document.getElementById('YOUR IFRAME').contentDocument.location.reload(true);
回答by Vasile Alexandru Peste
You can use this simple method
你可以使用这个简单的方法
function reloadFrame(iFrame) {
iFrame.parentNode.replaceChild(iFrame.cloneNode(), iFrame);
}
回答by pery mimon
2017:
2017年:
If it in on same domain just :
如果它在同一个域中:
iframe.contentWindow.location.reload();
will work.
将工作。
回答by Tony
Here is the HTML snippet:
这是 HTML 片段:
<td><iframe name="idFrame" id="idFrame" src="chat.txt" width="468" height="300"></iframe></td>
And my Javascript code:
还有我的 Javascript 代码:
window.onload = function(){
setInterval(function(){
parent.frames['idFrame'].location.href = "chat.txt";
},1000);}
回答by NotoriousPyro
If you use hash paths (like mywebsite.com/#/my/url) which might not refresh frames on switching hash:
如果您使用哈希路径(如 mywebsite.com/#/my/url)可能不会在切换哈希时刷新帧:
<script>
window.onhashchange = function () {
window.setTimeout(function () {
let frame = document.getElementById('myFrame');
if (frame !== null) {frame.replaceWith(frame);}
}, 1000);
}
</script>
Unfortunately, if you don't use the timeout JS may try to replace the frame before the page has finished loading the content (thus loading the old content). I'm not sure of the workaround yet.
不幸的是,如果您不使用超时,JS 可能会在页面完成加载内容之前尝试替换框架(从而加载旧内容)。我还不确定解决方法。
回答by lcharbon
Resetting the src attribute directly:
直接重置 src 属性:
iframe.src = iframe.src;
Resetting the src with a time stamp for cache busting:
使用时间戳重置 src 以进行缓存破坏:
iframe.src = iframe.src.split("?")[0] + "?_=" + new Date().getTime();
Clearing the src when query strings option is not possible (Data URI):
当查询字符串选项不可能时清除 src(数据 URI):
var wasSrc = iframe.src
iframe.onload = function() {
iframe.onload = undefined;
iframe.src = wasSrc;
}

