Search code examples
javascriptjqueryhtmlhistory.jshtml5-history

HTML5 History API initial load issue


I'm trying to store the first page information when the page first loaded. So that I can retrieve back the first page information when I click on the second page.

(Initial Page -> Page2 -> Initial Page)

After hours of working, I decided to store a global variable called firstLoad and use replaceState instead of pushState. It works now. But there is one problem, It could not go like this:

Initial Page -> Page2 -> Page3 -> Page2

When Page 3 goes back to Page 2, console shows:

GET http://localhost/[object%20Object] 404 (Not Found) 

I've Google-ed but I could not find any proper tutorial to deal with this issue, most of them suggest to use history.js, but i'm trying to learn how it works first. Any help would be appreciated!

<script>
$(function(){
    var firstLoad = 1;

    $('a').on('click', function(e){ 
        e.preventDefault();
        var path = this.href;
        var currentPath = window.location.pathname;
        loadContent(path);

        if(firstLoad==1){
            console.log(firstLoad);
            console.log(currentPath);
            firstLoad=0;
            history.replaceState(currentPath, '', '');
            history.pushState({},'',path);
        }else{
            console.log('Not first load')
            history.pushState(path,'',path);
        }
    });

    //Pop State
    $(window).on('popstate', function(e){
        var state = e.originalEvent.state;
        if(e.originalEvent && state){
            loadContent(state);
        }
    });

    //Load Content
    function loadContent(path){
        $.get(path, function(data){
            $('#result').html(data);
        });
    };

});
</script>

Solution

  • The issue is in this section of code.

    $(window).on('popstate', function(e){
        var state = e.originalEvent.state;
        if(e.originalEvent && state){
            loadContent(state);
        }
    });
    

    If we check the MDN page on Window.onpopstate we find that the state event property is the state object passed into functions such as pushState.

    the popstate event's state property contains a copy of the history entry's state object.

    The means that the jQuery event object property e.originalEvent.state is the object you pass in on pushState. You could use this object for storing data, but your loadContent function expects a string for the URL, not an object.

    I think you actually want to use document.location in your popstate handler.

    $(window).on('popstate', function(e){
        loadContent(document.location);
    });