iframe
是 HTML 中的一个元素,用于在当前网页中嵌入另一个 HTML 文档。通过 JavaScript 控制 iframe
刷新,可以实现动态更新嵌入内容的功能。
iframe
内容,提升用户体验。iframe
中,便于管理和维护。iframe
可以隔离不同域的内容,减少安全风险。iframe
:嵌入的文档与父页面同源(协议、域名、端口相同)。iframe
:嵌入的文档与父页面不同源。iframe
刷新<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>控制 iframe 刷新</title>
</head>
<body>
<button onclick="refreshIframe()">刷新 iframe</button>
<iframe id="myIframe" src="same-origin-page.html"></iframe>
<script>
function refreshIframe() {
var iframe = document.getElementById('myIframe');
iframe.src = iframe.src; // 重新设置 src 属性以刷新内容
}
</script>
</body>
</html>
iframe
刷新对于跨域 iframe
,由于同源策略的限制,直接操作 iframe
的内容会受到限制。可以通过 postMessage
API 进行跨域通信。
父页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>控制跨域 iframe 刷新</title>
</head>
<body>
<button onclick="refreshCrossDomainIframe()">刷新跨域 iframe</button>
<iframe id="crossDomainIframe" src="https://example.com/cross-domain-page.html"></iframe>
<script>
function refreshCrossDomainIframe() {
var iframe = document.getElementById('crossDomainIframe');
iframe.contentWindow.postMessage('refresh', 'https://example.com');
}
</script>
</body>
</html>
跨域 iframe
页面(cross-domain-page.html
):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>跨域页面</title>
</head>
<body>
<h1>这是一个跨域页面</h1>
<script>
window.addEventListener('message', function(event) {
if (event.origin !== 'https://your-origin.com') return; // 验证消息来源
if (event.data === 'refresh') {
location.reload(); // 刷新页面
}
});
</script>
</body>
</html>
iframe
不刷新原因:
src
属性未正确设置。解决方法:
src
属性都重新赋值。iframe.src = 'page.html?t=' + new Date().getTime();
。原因:
解决方法:
event.origin
)。通过以上方法,可以有效控制和刷新 iframe
,并解决常见的相关问题。
领取专属 10元无门槛券
手把手带您无忧上云