[英]Reload iframe only when iframe contents are new?
Short version: 简洁版本:
How could an HTML file that has an iframe
pointing to another HTML file on the same server automatically reload that iframe
whenever the iframe
's content is new ? 每当
iframe
的内容是新的时,具有iframe
指向同一服务器上另一个HTML文件的HTML文件如何自动重新加载该iframe
?
Context: 语境:
I'm using an HTML/Javascript file to watch for new instructions from a Python program. 我正在使用HTML / JavaScript文件来查看Python程序中的新指令。 The Python program rewrites a simple HTML file when there are new instructions to see.
有新的说明要看时,Python程序将重写一个简单的HTML文件。
So my easy solution is a bit of Javascript that forces a reload of the iframe
src every second. 因此,我的简单解决方案是使用Javascript强制每秒重新加载
iframe
src。
However, this causes a flash of the content every time the iframe
loads, and most of the time the information isn't new. 但是,这会在每次加载
iframe
时(大多数情况下不是新信息)都会刷新内容。
Instead, I'd prefer for the HTML file to only force a reload of the iframe
src when it's new. 相反,我希望HTML文件仅在新文件时才强制重新加载
iframe
src。 Is this possible? 这可能吗?
You can use an AJAX request to check if the iframe
has changed. 您可以使用AJAX请求来检查
iframe
是否已更改。
var value;
(function check() {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/url/toIframe'); // change this to the correct URL
xhr.addEventListener('load', function() {
if(value === undefined) {
value = this.responseText;
} else if(value != this.responseText) {
value = this.responseText;
// refresh iframe!
}
setTimeout(check, 1000); // check again in another second
});
xhr.send();
})();
This makes requests to the server to see if the content has changed. 这向服务器发出请求,以查看内容是否已更改。 There is one second between each the end of a request and the start of the next check.
在请求结束和下一次检查开始之间有一秒钟的时间。 (And currently, there is no error handling if the server goes down.)
(目前,如果服务器出现故障,将没有错误处理。)
FYI, if the server sends a Last-Modified
header, you could actually make a HEAD request and just check that header. 仅供参考,如果服务器发送了
Last-Modified
标头,则实际上您可以发出HEAD请求,只需检查该标头即可。 If you don't know what I am talking about, don't worry about it. 如果您不知道我在说什么,就不用担心。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.