Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload page when user returns from other tab

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

like image 789
R.G. Avatar asked Nov 13 '15 07:11

R.G.


1 Answers

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

like image 66
Anshul Mishra Avatar answered Sep 18 '22 10:09

Anshul Mishra