7

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).

R.G.
  • 831
  • 1
  • 8
  • 16

1 Answers1

11

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

Community
  • 1
  • 1
Anshul Mishra
  • 1,706
  • 2
  • 15
  • 38