I work on some kind of website that places importance on being up-to-date. For that purpose, I need to refresh the page when the user switches from another tab to the tab with the website.
Is there a way to do this with JavaScript / jQuery? I know that location.reload();
is used to refresh a page, but I don't know how to tell JavaScript to do this when the tab becomes active again (and only once then).
You can use this:
var vis = (function(){
var stateKey, eventKey, keys = {
hidden: "visibilitychange",
webkitHidden: "webkitvisibilitychange",
mozHidden: "mozvisibilitychange",
msHidden: "msvisibilitychange"
};
for (stateKey in keys) {
if (stateKey in document) {
eventKey = keys[stateKey];
break;
}
}
return function(c) {
if (c) document.addEventListener(eventKey, c);
return !document[stateKey];
}
})();
Usage:
var visible = vis(); // gives current state
vis(aFunction); // registers a handler for visibility changes`
vis(function(){
document.title = vis() ? 'Visible' : 'Not visible';
});
You can readabout this here:
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.