NOTE: history.pushState() now supported - see other answers.
You cannot change the entire URL without redirecting, you can change the hash instead.
hash is the part of the URL that comes after the # character. This was originally intended to direct you (locally) to sections of your HTML document, but you can read and modify it through javascript to use it as a global variable.
When applied well, this method is useful in two ways:
- browser history will remember every other step you took (as URL + hash changed)
- you may have an address that not only refers to a specific html document, but also gives your javascript a hint about what to do. This means that you end up pointing to the state inside your web application.
To change the hash, you can do:
document.location.hash = "show_picture";
To keep track of hash changes, you need to do something like:
window.onhashchange = function(){ var what_to_do = document.location.hash; if (what_to_do=="#show_picture") show_picture(); }
Of course, a hash is just a string, so you can do what you like. For example, you can put an entire object there if you use JSON to format it.
There are very good jQuery libraries to do extra things with them.
david Jun 25 2018-11-11T00: 00Z
source share