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:
Detect if browser tab is active or user has switched away
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With