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