Can I prevent history.popstate from triggering on initial page-load?

我只是一个虾纸丫 提交于 2019-11-27 06:30:37

Using the native HTML5 History API you're going to run into some problems, every HTML5 browser handles the API a little bit differently so you can't just code it once and expect it to work without implementing workarounds. History.js provides a cross-browser API for the HTML5 History API and a optional hashchange fallback for HTML4 browsers if you want to go down that route.

For upgrading your website into a RIA/Ajax-Application you can use this code snippet: https://github.com/browserstate/ajaxify

Which is part of the longer article Intelligent State Handling which goes into explanations about hashbang, hashes and the html5 history api.

Let me know if you need any further help :) Cheers.

You need to get the event.originalEvent

// Somewhere in your previous code
if (history && history.pushState) {
  history.pushState({module:"leave"}, document.title, this.href);
}


$(window).bind("popstate", function(evt) {
  var state = evt.originalEvent.state;
  if (state && state.module === "leave") {
    $.getScript(location.href);
  }
});

When the popstate event is fired on page load it will not have a state property in the event object. This allows you to check if the event is fired for a page load or not.

window.onpopstate = function (event) {
  if (event.state) {
    // do your thing
  } else {
    // triggered by a page load
  }
}

When the browser first loads, it always fires a popstate event. So you need to determine if this popstate is yours or not.

When you do your pushState, make sure you have a state object. That way you can check it later.

Then on the popstate handler, check the state object :)

$(function() {
    $(window).bind("popstate", function(data) {
        if (data.state.isMine)
            $.getScript(location.href); 
    });
});

// then add the state object
history.pushState({isMine:true},title,url);

Let me know if you need any more help :)

I use this to change bar adress and save current state, including current html body, and i reload it on back bouton click without any other ajax call. All is saved in your browser :

  1. $(document).ajaxComplete(function(ev, jqXHR, settings) {
    
        var stateObj = { url: settings.url, innerhtml: document.body.innerHTML };
        window.history.pushState(stateObj, settings.url, settings.url);
    });
    
    
    window.onpopstate = function (event) {
        var currentState = history.state;
        document.body.innerHTML = currentState.innerhtml;
    };
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!