Ajax with history.pushState and popstate - what do I do when popstate state property is null?

前端 未结 6 934
遥遥无期
遥遥无期 2021-02-07 01:18

I\'m trying out the HTML5 history API with ajax loading of content.

I\'ve got a bunch of test pages connected by relative links. I have this JS, which handles clicks on

6条回答
  •  说谎
    说谎 (楼主)
    2021-02-07 01:58

    I ran into the same issue as the original question. This line

    var initialPop = !popped && location.href == initialURL;
    

    should be changed to

    var initialPop = !popped;
    

    This is sufficient to catch the initial pop. Then you do not need to add the original page to the pushState. i.e. remove the following:

    var home = 'index.html';
    history.pushState({page:home}, null, home);
    

    The final code based on AJAX tabs (and using Mootools):

    if ( this.supports_history_api() ) {
        var popped = ('state' in window.history && window.history.state !== null)
        ,   changeTabBack = false;
    
        window.addEvent('myShowTabEvent', function ( url ) {
           if ( url && !changingTabBack )
               setLocation(url);
           else
               changingTabBack = false;
           //Make sure you do not add to the pushState after clicking the back button
        });
    
       window.addEventListener("popstate", function(e) {
           var initialPop = !popped;
           popped = true;
           if ( initialPop )
               return;
    
           var tabLink = $$('a[href="' + location.pathname + '"][data-toggle*=tab]')[0];
           if ( tabLink ) {
               changingTabBack = true;
               tabLink.tab('show');
           }
       });
    }
    

提交回复
热议问题