21

I am writing a complex AJAX application at the moment and the entire site has clean URLs. At the moment PHP creates the basic layout for each page however I don't want to have to navigate away from each page when the user clicks on a link, and I don't want to have a hash in the URL because it won't fit with the rest of the site. I know that this has cropped up loads before on the site and it seems to be quite commonly asked but I was wondering if there was a neat HTML5 way of just appearing to change the URL in the address bar even if it technically remains on the same page.

Thomas Denney
  • 1,458
  • 1
  • 15
  • 24

2 Answers2

52

You can do it with history.pushState, but only in browsers that support it. Just try the following line in your browsers JavaScript-Console.

history.pushState({},"URL Rewrite Example","https://stackoverflow.com/example")

More on that in The pushState() method (Mozilla Developer)

Similar question How do I, with JavaScript, change the URL in the browser without loading the new page?

Community
  • 1
  • 1
Tilman Schweitzer
  • 1,377
  • 9
  • 10
  • 4
    Make sure to follow the [Same Origin Policy](https://en.wikipedia.org/wiki/Same-origin_policy) else you will face a **SecurityError: The operation is insecure**. I mean if your domain is http://example.com you only are allowed to use history.pushState for something like `http://example.com/Someotherpage`, you are not allowed to use http://example.org instead to prevent phishing. If there wasn't such a constraint, everybody could create a fake page similar to google.com and after it was loaded, he could make URL to look http://google.com! [More](https://stackoverflow.com/q/13348766/4344976) – Muhammad Musavi May 08 '18 at 10:53
6

As others have stated, HTML5's history.pushstate is the way to go. Try browsing a repo on github to see it in action (https://github.com/visionmedia/express).

Trouble is the only version of IE that supports history.pushstate is IE10, which kinda sucks.

Plenty of sites use hashbang #! URL's such as Twitter (e.g. https://twitter.com/#!/Sironfoot ). The hashbang is a URL pattern agreed on by search engines so that they can still trawl and index a heavily Ajax powered website (more info here http://code.google.com/web/ajaxcrawling/docs/specification.html), so you could go that route.

The only other approach is to use history.pushstate for browsers that support it, and fall back to full-page refreshes for non-supporting browsers.

Sunday Ironfoot
  • 12,268
  • 13
  • 71
  • 89
  • If you happen to find this answer after 2015, please note that the Google #! crawling specifications have been deprecated: https://webmasters.googleblog.com/2015/10/deprecating-our-ajax-crawling-scheme.html – Hauke P. Sep 19 '19 at 15:43