Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

disable page refresh on lose focus

I am wondering if there is a way to disable an automatic page refresh when a page loses focus. I have it setup to refresh when it gains focus again already using this:

window.onblur= function() {window.onfocus= function () {location.reload(true)}};

that I found from here. I originally had the page auto refresh by using:

<meta http-equiv="refresh" content="60"/>

Which reloads the page every 60 seconds regardless of state.

I want to make the page have the auto refresh only when in focus with the initial refresh coming when the page gains focus again. After the gain of focus it should refresh at the time interval until focus is lost.

Thanks

like image 404
thekgb09 Avatar asked Jun 15 '13 21:06

thekgb09


2 Answers

You can't override this kind of refresh, you should probably use a JS timer to refresh, something like this (after removing the <meta http-equiv="refresh" content="60" /> tag):

var hasFocus;

window.onblur = function() {
    hasFocus = false;
}

window.onfocus = function(){
    hasFocus = true;
}

setInterval(reload, 60*1000);

function reload(){
    if(hasFocus){
        location.reload(true);
    }
}
like image 60
Mostafa Berg Avatar answered Sep 30 '22 17:09

Mostafa Berg


I ended up modifying the code from Mostafa Torbjørn Berg to maintain the refresh on focus and have the page automatically refresh every 60 seconds while the page has focus.

var hasFocus= true;
window.onblur = function() {
    hasFocus = false;
}
window.onfocus = function(){
    location.reload(true);
}
setInterval(reload, 60*1000);
function reload(){
    if(hasFocus){
        location.reload(true);
    }
}
like image 27
thekgb09 Avatar answered Sep 30 '22 17:09

thekgb09