简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM