简体   繁体   中英

popstate fire on page load

$(window).on('popstate', function(){
    window.history.go(-1);
});

I have a page use popstate when user click back button

but in some browser, popstate fire on page load instead back button click.

it happen in Safari and touch device.

The easiest hack/solution, is to add the popstate listener right after the initial page load, in a setTimeout.

 setTimeout( function() {
    window.addEventListener( 'popstate', myPopStateHandler, false );
  }, 500 );

I'm weary of throwing a setTimeout in for a resolution, always seems like a kludge. But for now, hey it works.

Adding a flag to detect page load fixed this for me.

Edit: added Safari browser detection, otherwise first click of back button won't trigger popstate event in Firefox or Chrome.

var isSafari = /^((?!chrome).)*safari/i.test(navigator.userAgent),
    firstLoad = true;
$(window).on('popstate', function(){
    if (isSafari && firstLoad) {
        firstLoad = false;
        return;
    } else {
        // run your popstate code
    }
});

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