Search code examples
javascriptbrowser-historypushstatehistory.jsbrowser-state

Pushstate doesn't fire when pushed URL is the same as current


I've built a primitive routing function for a site I'm working on.
The idea is to check the incoming URL and then send the browser to the appropriate part of the site.

I've noticed that pushState doesn't fire if the incoming URL is the same as the one that it's supposed to push to. Meaning, if I go to domain.com/journal it won't fire. The URL is the same as the one the router is supposed to push to: History.pushState({ id: 'journal' }, site.title+' — '+'Journal', site.url+'/journal' );).

But if I put domain.com/journal/ instead, it will fire. Why is that?


Simplified routing code

setTimeout(function() {
      uri = window.location.pathname.replace(/^\/([^\/]*).*$/, '$1');
      if(uri === 'journal') {
        uri = window.location.pathname.split( '/' );
        if(uri[2]) {
          History.pushState({ id: 'post', no: uri[2] }, site.title+' — '+'Journal', site.url+'/journal/'+uri[2] );
        } else {
          History.pushState({ id: 'journal' }, site.title+' — '+'Journal', site.url+'/journal' );
        }
      } else if(uri === 'contact') {
        History.pushState({ id: 'contact' }, site.title+' — '+'Contact', site.url+'/contact' );
      } else {
        History.pushState({ id: 'gallery' }, site.title, site.url );
      }
}, 1);

History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
    var State = History.getState(); // Note: We are using History.getState() instead of event.state  
    Roots.common.history(State);
}

history: function(State) {
    navigate(State.data.id, State.data.no);
},

navigate: function(section, no) {
  if(section === 'gallery') {
    // do gallery stuff
  } else if(section === 'journal') {
    // do journal stuff
  } else if(section === 'contact') {
    // do contact stuff
  } else if(section === 'post') {
    // do post stuff
  }
}

Solution

  • The simple solution to make it fire no matter what is to send random data together with the pushState

    History.pushState({ id: 'gallery', randomData: window.Math.random() }, site.title, site.url );