【问题标题】:Pushstate doesn't fire when pushed URL is the same as current当推送的 URL 与当前 URL 相同时,Pushstate 不会触发
【发布时间】:2014-07-21 22:41:11
【问题描述】:

我已经为我正在开发的网站构建了一个原始路由功能。
这个想法是检查传入的 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
  }
}

【问题讨论】:

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


    【解决方案1】:

    无论什么都让它触发的简单解决方案是与 pushState 一起发送随机数据

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-08
      • 2022-01-22
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      • 2013-08-10
      • 2020-10-08
      • 1970-01-01
      相关资源
      最近更新 更多