10

Is it possible to get the html of the last state pushed to history stack, something like this:

history.pushState(null, null, {html: $('body').html()});

Change the window location:

window.location = url;

Now from the new location:

window.addEventListener('popstate', function(event) {
    // back to the last state - event.state.html
}
history.back() // That what's firing the popstate event? 
shmnsw
  • 569
  • 1
  • 10
  • 24

2 Answers2

1

I searched for the request to get the html of the last state pushed to history, but did not get satisfactory answers. But I have an idea for you, why dont you try to save the html of the state before pushing it to history? This is quite possible using client side (cookies) or server side (session) variables, which can be retrieved even after the things have been pushed back in history.

Victor Juliet
  • 842
  • 10
  • 21
0

The pushState method takes the state object as the first argument, where you're passing in null:

Example of pushState() method

var stateObj = { foo: "bar" };

history.pushState(stateObj, "page 2", "bar.html");

For your example:

//object goes in first argument
history.pushState({ html: $('body').html() }, "Title of Page", "Url to update address bar" );

//On PopState, you have access to event.state
window.addEventListener('popstate', function(event) {
    var priorStateObj = event.state;
    console.log(priorStateObj.html);
}

What concerns me is that you seem to then want to potentially document.write() that HTML back to the page? If so, I would try to avoid that, as explained in this SO thread: Why is document.write considered a "bad practice"?

As far as saving the entire HTML of the body, that's tricky. In Firefox, for example, there is a limit of 640 kilobits. If your HTML could possibly exceed that amount (likely), you'll want to just save information that you can use to recreate what you need. Try saving an Object with just the info you need to populate the page using JavaScript/jQuery/etc.

The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored after the user restarts the browser, we impose a size limit of 640k characters on the serialized representation of a state object. If you pass a state object whose serialized representation is larger than this to pushState(), the method will throw an exception. If you need more space than this, you're encouraged to use sessionStorage and/or localStorage.

Lots more good info here:

https://developer.mozilla.org/en-US/docs/Web/API/History_API

Community
  • 1
  • 1
Sean Kendle
  • 2,956
  • 1
  • 21
  • 27