Pop the last state from history
Asked Answered
R

2

13

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? 
Rycca answered 17/4, 2015 at 18:28 Comment(1)
"Something like this" - so doesn't it work?Womack
C
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.

Cumquat answered 19/5, 2015 at 4:27 Comment(2)
This should be a comment, not an answer.Gotha
I am not allowed to add comments at this stage on questionsCumquat
F
1

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

Fugato answered 26/1, 2017 at 14:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.