$(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.
$(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
}
});