当推送的URL与当前URL相同时,Pushstate不会触发

时间:2014-06-01 20:02:35

标签: javascript browser-history pushstate history.js browser-state

我为我正在处理的网站构建了原始路由功能 我们的想法是检查传入的URL,然后将浏览器发送到站点的相应部分。

我注意到如果传入的URL与它应该推送的URL相同,则pushState不会触发。意思是,如果我去domain.com/journal它就不会被激怒。该URL与路由器应推送到的URL相同:History.pushState({ id: 'journal' }, site.title+' — '+'Journal', site.url+'/journal' );)。

但如果我改为domain.com/journal/,它就会发射。那是为什么?


简化的路由代码

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
  }
}

1 个答案:

答案 0 :(得分:0)

无论是将随机数据与pushState一起发送的简单解决方案,都可以解决这个问题。

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