Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the 'data' in window.history.replaceState

We are working on a project using window.history.replacestate. Unfortunately we aren't very good at javascript.

Essentially we are using it to replace any number of shortlinks to the 'root' link. For example :

domain.com/fJfk8
domain.com/9dkDl
domain.com/fjgdD

would all 'appear' as :

domain.com/nice_url

It doesn't have to work so we'll put the javascript in the page and in the browsers it does then great and if it doesn't, they get the shortcode.

Note : we don't want history !

So we are just using :

window.history.replaceState('Object','Nice URL Title', '/nice_url');

The question is that this appears to work but we don't understand the 'Object' (data) part.

What exactly is it ?

like image 651
Mike Frederico Avatar asked Sep 19 '11 08:09

Mike Frederico


1 Answers

You can set the Object parameter to arbritary data, which will be available in the state parameter of the event object which is available in the popstate event.

In other words, you can set it to whatever you want, to help you restore the webpage to the desired state when the user navigates through their history.

For more information, see the MDC documentation on window.history.

window.history.replaceState({
    foo: 'bar'
}, 'Nice URL Title', '/nice_url');

window.onpopstate = function (e) {
    if (typeof e.state == "object" && e.state.foo == "bar") {
        alert("Blah blah blah");
    }
};

window.history.go(-1);
like image 145
Matt Avatar answered Nov 15 '22 03:11

Matt