我想重新加载一个<iframe>使用JavaScript。到目前为止,我发现最好的方法是将iframe的src属性设置为自身,但这不是很干净。什么好主意吗?
当前回答
将空字符串附加到iFrame的src属性也会自动重新加载它。
document.getElementById('id').src += '';
其他回答
在我的例子中,简单地替换iframe元素的src属性并不能令人满意,因为在加载新页面之前,人们会看到旧的内容。如果你想提供即时的视觉反馈,这种方法会更好:
var url = iframeEl.src;
iframeEl.src = 'about:blank';
setTimeout(function() {
iframeEl.src = url;
}, 10);
由于同源策略,当修改指向不同域的iframe时,这将不起作用。如果你的目标浏览器更新,可以考虑使用HTML5的跨文档消息传递功能。您可以在这里查看支持此功能的浏览器:http://caniuse.com/#feat=x-doc-messaging。
如果你不能使用HTML5的功能,那么你可以遵循这里列出的技巧:http://softwareas.com/cross-domain-communication-with-iframes。该博客条目也很好地定义了问题。
如果你尝试了所有其他的建议,但没有一个奏效(就像我一样),这里有一些你可以尝试的可能有用的建议。
HTML
<a class="refresh-this-frame" rel="#iframe-id-0">Refresh</a>
<iframe src="" id="iframe-id-0"></iframe>
JS
$('.refresh-this-frame').click(function() {
var thisIframe = $(this).attr('rel');
var currentState = $(thisIframe).attr('src');
function removeSrc() {
$(thisIframe).attr('src', '');
}
setTimeout (removeSrc, 100);
function replaceSrc() {
$(thisIframe).attr('src', currentState);
}
setTimeout (replaceSrc, 200);
});
我最初打算通过RWD和跨浏览器测试来节省一些时间。我想创建一个快速的页面,里面有一堆iframes,组织成我可以随意显示/隐藏的组。从逻辑上讲,您希望能够轻松快速地刷新任何给定的帧。
我应该指出的是,我目前正在进行的项目,也就是在这个测试台上使用的项目,是一个单页站点,站点的位置有索引(例如index.html#home)。这可能与为什么我不能得到任何其他解决方案来刷新我的特定框架有关。
话虽如此,我知道这不是世界上最干净的东西,但它对我的目的很有效。希望这能帮助到一些人。现在,如果我能弄清楚如何保持iframe在每次iframe内有动画时滚动父页…
编辑: 我意识到这并没有像我所希望的那样“刷新”iframe。它将重新加载iframe的初始源。仍然不明白为什么我不能得到任何其他的选择工作..
更新: 我不能得到任何其他方法工作的原因是因为我在Chrome中测试它们,Chrome不允许你访问iframe的内容(解释:当iframe从本地html文件加载本地html文件时,是否有可能未来的Chrome版本支持contentWindow/contentDocument ?)如果它不是来自同一个位置(据我所知)。经过进一步测试,我也无法访问FF中的contentWindow。
修改JS
$('.refresh-this-frame').click(function() {
var targetID = $(this).attr('rel');
var targetSrc = $(targetID).attr('src');
var cleanID = targetID.replace("#","");
var chromeTest = ( navigator.userAgent.match(/Chrome/g) ? true : false );
var FFTest = ( navigator.userAgent.match(/Firefox/g) ? true : false );
if (chromeTest == true) {
function removeSrc() {
$(targetID).attr('src', '');
}
setTimeout (removeSrc, 100);
function replaceSrc() {
$(targetID).attr('src', targetSrc);
}
setTimeout (replaceSrc, 200);
}
if (FFTest == true) {
function removeSrc() {
$(targetID).attr('src', '');
}
setTimeout (removeSrc, 100);
function replaceSrc() {
$(targetID).attr('src', targetSrc);
}
setTimeout (replaceSrc, 200);
}
if (chromeTest == false && FFTest == false) {
var targetLoc = (document.getElementById(cleanID).contentWindow.location).toString();
function removeSrc() {
$(targetID).attr('src', '');
}
setTimeout (removeSrc, 100);
function replaceSrc2() {
$(targetID).attr('src', targetLoc);
}
setTimeout (replaceSrc2, 200);
}
});
如果你使用Jquery,那么有一行代码。
$('#iframeID',window.parent.document).attr('src',$('#iframeID',window.parent.document).attr('src'));
如果你们是和同一个家长一起工作的话
$('#iframeID',parent.document).attr('src',$('#iframeID',parent.document).attr('src'));
window.frames['frameNameOrIndex'].location.reload();