简体   繁体   中英

History.pushState and page refresh

I started looking at HTML5 new history API

However, I have one question. How can one handles the page refresh?

For example a user clicks a link, which is handled by a js function, which

asynchronously loads the content of the page

changes the URL with history.pushState()

The the user refreshes the page, but the URL of course does not exist on the server

How do you handle situations like this? With the hash solution there was no issue there

Thanks

This does require the server-side support. The ideal use of .pushState is to allow URLs from JavaScript applications to be handled intelligently by the server.

This could be either by re-serving the same JavaScript application, and letting it inspect window.location , or by rendering the content at that URL on the server as you would for a normal web application. The specifics obviously vary depending on what you're doing.

You need to perform server side redirection for copy and pasted fake URLs It all depends on what server side technology you're using. There is no JavaScript way but writing a crazy function in your 404 page that redirect user based on incoming URL that is not a good solution.

The the user refreshes the page, but the URL of course does not exist on the server

What do you mean by this? I have a feeling your assumption is wrong. Actually yes, the point is it is the developer who should provide (serverside or clientside) implementation of url-to-pagestate correspondence.

If, once again, I've get the question right.

If you are using ASP.NET MVC on your server, you can add the following to your RegisterRoutes function:

       routes.MapRoute(
            name: "Default",
            url: "{*url}",
            defaults: new { controller = "Home", action = "Index" }
       );

This will send all requests to Index action of your HomeController and your UI will handle the actual route.

For people looking for a JS-only solution, use the popstate event on window . Please see MDN - popstate for full details, but essentially this event is passed the state object you gave to pushState or replaceState . You can access this object like event.state and use it's data to determine what to do, ie show an AJAX portion of a page.

I'm not sure if this was unavailable in 2011 but this is available in all modern browsers (IE10+), now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM