最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - onpopstate handler - ajax back button - Stack Overflow

programmeradmin4浏览0评论

I'm using pushState to create meaningful urls for ajax content on my site. I want to refresh the ajax content when the user hits the forward or back buttons. I'm having problems however as chrome (correctly) impliments onpopstate on both 'history traversal' (forward/back buttons) and 'the end' (page load). I'd like to create an onpopstate handler that differentiates between page load and history traversal, as I don't want to refresh my ajax content if it's already just been loaded successfully. Can anybody help me with differentiating between the two?

window.onpopstate = function (event) {
    // If : Forward/back button pressed
        // Reload any ajax content with new variables
    // Else : Page load plete
        // Do nothing - content already loaded and correct
}

See for more details on chrome and onpopstate.

Thanks

I'm using pushState to create meaningful urls for ajax content on my site. I want to refresh the ajax content when the user hits the forward or back buttons. I'm having problems however as chrome (correctly) impliments onpopstate on both 'history traversal' (forward/back buttons) and 'the end' (page load). I'd like to create an onpopstate handler that differentiates between page load and history traversal, as I don't want to refresh my ajax content if it's already just been loaded successfully. Can anybody help me with differentiating between the two?

window.onpopstate = function (event) {
    // If : Forward/back button pressed
        // Reload any ajax content with new variables
    // Else : Page load plete
        // Do nothing - content already loaded and correct
}

See http://code.google./p/chromium/issues/detail?id=63040 for more details on chrome and onpopstate.

Thanks

Share Improve this question asked Mar 10, 2011 at 9:42 user623520user623520
Add a ment  | 

3 Answers 3

Reset to default 8

One way would be to initialize a variable to false on page load, and then on your popstate event, check that variable. If it's still false, set it to true and do nothing. From then on all of your other popstate events should be only from back/forward events.

var loaded = false;

window.onpopstate = function(e) {
    if (!loaded) {
        loaded = true;
        return;
    } else {
        // run your stuff...
    }
}

The object passed to the onpopstate function will have a state member, which will be null on the page load, so you could do something like this:

window.onpopstate = function(event) {
  if(event && event.state) {
    // ...
  }
}

//example: http://www.nseri./news/5536

window.onpopstate = function(e) {
     var count = String(location.pathname).split('/').length;
     if (count<4) {
          location.href = location.href;
     }else {
          $.ajaxLoad(location.pathname);
     }
}
发布评论

评论列表(0)

  1. 暂无评论