HTML and CSS Reference
In-Depth Information
In terms of behavior, most browsers agree in that if you change the current page's hash,
the browser saves that state in the forward/backward queue, updates the displayed
URL, and does not request a new page from the server. On the surface, that sounds
just like what we're looking for. However, there are several browser quirks (race con-
ditions, etc.) that make it hard to get consistent and reliable results when dealing with
hash changes.
In particular, older browsers don't all support the hashchange event, which is very
helpful in monitoring the state of the URL hash in case a user copies and pastes a URL
into the address bar. Without that event, you must poll the URL hash using a timer.
Fortunately, all this mess is generally taken care of by various helper libraries. One
particularly useful library is History.js ( https://github.com/balupton/history.js ) , which
attempts to use the new HTML5 History API enhancements and falls back to URL hash
management automatically.
The above code example stores a simple state in the URL (“?show”). This is good for
the copy/paste (or bookmarking) use case, as the entirety of the state is in the URL and
thus restorable.
If you have a more complex set of states to manage, and copy/paste or bookmarking
is not important, you can actually store a much richer and more complex set of states
with each entry. This complex state is saved with an entry, and then retrieved and sent
back to your application via the popstate event handler as the user navigates back with
the back button.
The first parameter to pushState(...) / replaceState(...) is the state object, which can
be any arbitrarily complex object that you need, as long as it's serializable to a string
value. For example:
window.addEventListener("popstate", function(e){
alert("Current state data: " + JSON.stringify(e. state ));
}, false);
window.pushState( {foo:"bar"} , null, "?foobar");
window.pushState( {bar:"baz"} , null, "?barbaz");
history.back(); // triggers popstate to go back to the "?foobar" page/state
Browsers currently don't support the second parameter, which is a
“title” for the new state, so just pass null or an empty string for that
parameter.
See Also
For more information about using the API, see the following MDC entry: https://devel
oper.mozilla.org/en/DOM/Manipulating_the_browser_history . For more information
about History.js, see the github repo at https://github.com/balupton/history.js .
 
Search WWH ::




Custom Search