Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pushState and back button works but content doesn't change

It does load a new page and the url does update, but when I press the back button, only the url has changed without refreshing but the content doesn't.

$('button').click(function(){
  window.history.pushState({}, '', 'page2.php');
  $('body').html('<div class="loading.gif"></div>');

  //Load Page
  $.get('page2.php', function(data){
    $('body').html(data);
  };

  //Edited 
  $(window).bind('popstate', function(){
    //What should I code here??
  });
});
like image 211
Dale A. Almaraz Avatar asked Jul 31 '14 18:07

Dale A. Almaraz


People also ask

What is the difference between pushState and replaceState?

The big difference is, that while pushState will create a new entry in the browser's history, replaceState will only replace the current state. As a side effect of this, using the replaceState method will change the URL in the address bar, without creating a new history entry.

Does history pushState reload page?

The history. pushState() method can be used to push a new entry into the browser's history—and as a result, update the displayed URL—without refreshing the page. It accepts three arguments: state , an object with some details about the URL or entry in the browser's history.

How do you trigger a Popstate?

The popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history. back() or history. forward() in JavaScript). Browsers tend to handle the popstate event differently on page load.

What is window history pushState?

In an HTML document, the history. pushState() method adds an entry to the browser's session history stack.


1 Answers

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;
    };
    
like image 85
ghooz Avatar answered Oct 24 '22 05:10

ghooz