I have a website on an AJAX and it is necessary that when clicking on a link, an AYAX worked (that is, the page does not reload, but loads), I do this:

location.href=bla-bla; return false; 

but as I thought it didn't work. What are the solutions? That is, it is necessary to insert the URL of the link to which the user clicks into the address line.

3 answers 3

 function setLocation(curLoc){ try { history.pushState(null, null, curLoc); return; } catch(e) {} location.hash = '#' + curLoc; } 
  • Thanks It works. - Yoharny Babay
  • Good day. Is it possible to somehow move through the history using the browser buttons forward / back? Now when you press the "back" button, the URl changes, but does not move - MrFranke
  • @MrFranke so you need to catch this event (change url) - lampa
  • Why try - catch instead of checking? - Qwertiy
  window.history.pushState("object or string", "Title", "/new-url"); 

The HTML5 specification also defines a different, more complex and more
reliable way to manage your browsing history
history.pushState() and popstate events. When moving to a new state, a web application can call the history.pushState() method to add this state to the browsing history.

In the first argument, the method is passed an object containing all the information necessary to restore the current state of the application. Any object that can be converted to a string by calling the JSON.stringify() method, as well as some built-in types, such as Date and RegExp , are suitable for this purpose.

The second argument is an optional title (a simple text string) that the browser can use to identify the saved state in the browsing history (for example, in the Back button menu).

The third optional argument is the URL string that will be displayed as the current state address. Relative URLs are interpreted relative to the current address of the document and often define only the part of the URL corresponding to the fragment identifier, such as #state .

Associating various application states with your own URLs allows the user to bookmark the internal states of the application, and if enough information is specified in the URL bar, the application can restore this state at launch using a bookmark.

© David Flanagan. "Javascript. Detailed guide"

It is this API that Vkontakte uses, for example - the address of the pages changes completely without # .

It is worth noting that window.history... not necessary to write, simply history... enough. It should also be mentioned that this API does not work in all browsers, for example, as stated in a similar question in English SO , it does not exist in IE9.

    It even works in IE8:

     function setLocation(curLoc){ location.href = curLoc; location.hash = curLoc; } 

    Only the function I call with the hash:

     setLocation('#book/' + id);