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 ?
Context:
I'm using an HTML/Javascript file to watch for new instructions from a Python program. The Python program rewrites a simple HTML file when there are new instructions to see.
So my easy solution is a bit of Javascript that forces a reload of the iframe
src every second.
However, this causes a flash of the content every time the iframe
loads, and most of the time the information isn't new.
Instead, I'd prefer for the HTML file to only force a reload of the iframe
src when it's new. Is this possible?
You can use an AJAX request to check if the iframe
has changed.
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. If you don't know what I am talking about, don't worry about it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.