Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore Safari's Initial Page Load popstate

I'm using pushState and generating the page view on popstate events based on the history.state of the current page.

If there is no history.state I (hope) to reload the document.

window.onpopstate = function(event) {
    if( window.history.state !== null ){
        // page was ajax created and history created by pushState
        // recreate with ajax
    }
    else{
        // page was loaded from server normally
        document.location.reload()
    }
}

At issue is Safari fires a popstate event on the initial page load. Chrome and Firefox fire popstate on the back/forward browser button.

I want to ignore the initial load popstate event on Safari (ideally without setTimeout and without browser detection).

Additionally, the site is a mix of links - some that will trigger pushState and some that will load normally from the server - so if a user is ten pages into navigation history and clicking the back button, the history will have a mix of pushState pages and non-pushState pages.

like image 575
tgrass Avatar asked Feb 10 '15 20:02

tgrass


1 Answers

I have solved the problem saving the initial order value obtained from window.history.state.order in a variable. When the on popstate event is triggered, the value previously stored is compared to the current order value. It they are the same then nothing is needed to be done (you have to ignore the initial popstate value triggered by Safari). Here you can see and example:

var initial_oder = window.history.state.order || 0;    
window.onpopstate = function(event) {
    if( window.history.state !== null && window.history.state.order !== initial_order){
        // page was ajax created and history created by pushState
        // recreate with ajax
    }
    else{
        // page was loaded from server normally
        document.location.reload()
    }
}

Hope this help!

like image 142
IIIRepublica Avatar answered Sep 24 '22 05:09

IIIRepublica