Do something on window.onpopstate or window.onload but never twice

7.1k views Asked by At

I would like to write a javascript code able to do something on either window.onpopstate or window.onload but never twice (note that chrome fires a popstate event both onload and when clicking the back navigation button)

I would like it to be compatible for major modern browsers (IE10 firefox chrome opera safari)

And i would prefer NOT to use any library - not even jquery.

Something like this (but with the right syntax of course):

window.onload || window.onpopstate = function(){
    window.alert("hello world");
}

Thanks

EDIT 1

With ur suggestions i have tried this:

var ranAlready=false;

window.onload = function(){
if (!ranAlready){
    window.alert("onload was true");
    ranAlready=true;
}
};

window.onpopstate = function(){
if (!ranAlready){
    window.alert("popstate was true");
    ranAlready=true;
}
};

But now im not sure how to set the variable back to false.. cuz it depends on the browser and so on..

EDIT 2

I need it to work more than once, because the user might click some ajax links, and so the page wont refresh but the url will change and thus he might click the back button. This means the variable has to be set back to false at some moment / but i dont know when..

1

There are 1 answers

7
htxryan On

The problem is that in Chrome, the "popstate" event is fired on page load, so the handler would run twice. You can fix this by checking the history state when running on popstate to detect if it's running on initial load.

function showAlert() {
    window.alert("hello world");
}
function showAlertOnPopState(){
    if (window.history.state == null){ // This means it's page load
        return;
    }
    showAlert();
}

window.onload = showAlert;
window.onpopstate = showAlertOnPopState;

Fiddle: http://jsfiddle.net/ER8zC/2/

Found the history.state trick here: Popstate on page's load in Chrome