Frage

Trying to understand the history API, the Mozilla explanation below suggests to me that even if the url you push to the history does not really exist on the server, a back button click from an external source will return the original page from which the pushState call was made:

Suppose http://mozilla.org/foo.html executes the following JavaScript:

var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");

This will cause the URL bar to display http://mozilla.org/bar.html, but won't cause the browser to load bar.html or even check that bar.html exists.

Suppose now that the user now navigates to google.com, then clicks back. At this point, the URL bar will display ...mozilla.org/bar.html, and the page will get a popstate event whose state object contains a copy of stateObj. The page itself will look like foo.html, although the page might modify its contents during the popstate event.

If we click back again, the URL will change to ...mozilla.org/foo.html, and the document will get another popstate event, this time with a null state object. Here too, going back doesn't change the document's contents from what they were in the previous step, although the document might update its contents manually upon receiving the popstate event.

I have created a test page in an MVC project that literally just associates a button click with the 2 lines of javascript from the above example. Clicking the button, as expected, changes the browser location from localhost to localhost/bar.html, and the back and forward buttons work as expected. But if I then navigate to google and press the back button, I get a 404 server error. Have I misunderstood the documentation? And how can I ammend the code so that a back button from an external source works, without creating an actual 'bar.html'?

War es hilfreich?

Lösung

In case anyone else is wondering about the same thing, I'm now using query strings appended to my real url rather than non-existent paths to push to history. This achieves what I wanted, i.e. I can push states, navigate to an external page, then hit the back button and retrieve the state by listening for a popstate.

(Admittedly I am still slightly confused by the Mozilla documentation which does suggest (to me at least!) that a fake path should work.)

Andere Tipps

pushstate is half of the equation....

You also need to listen for popstate:

window.addEventListener("popstate", function(e) {

    console.log(arguments)
    // read the arguments to figure out what state you need return to
    // change the page to however you need 

});

Add this function above and watch the console. What I do is save enough information in js variables so I can set the page as needed.

pushstate and popstate are very useful in html5 mobile development when you're creating a "single page web app". This is exactly how I use it and it works great.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top