Browser navigation with AJAX pages
Recently I came to this issue, and after a lot of googling around I found a simple and powerful solution so I thought it would be beneficial for everyone to know about it. It’s called jQuery Address, and you can find it on the page of Asual. Let’s download it now.
My main problem was that I’m hijaxing almost all of my links in my ASP.NET MVC application, and doing this prevented me from using the browser’s back and forth buttons. I could easily live with this, but my designer couldn’t so I had to come up with a solution. I must warn everyone that it was just pushed together in a hassle, and you could almost see the duct tape holding it together, but it works (for now).
So get the jQuery address plugin, and include it in your project. Then just call the $.address method of it on the anchor tags you wish to hijack – my example:
This initializes the logic, and you can see a nice #/pageURL appended to your query string. You can now go back and forth in your browser, even bookmark your pages, but doing so won’t result in any change, just the URL will change in the browser’s nav bar. But we needed just that!
Now my idea was that I would do this dead simple (and a bit simplistic). So I needed the URL’s part after the double-cross symbol, and then feed it with my browser. Fortunately, there’s an event for browser-originating events that result in URL changes in the Address plugin, which is called externalChange. I’ve come up with this solution:
var address = document.location.toString();
var newUri = address.split('#');
//Now you have your result here, do something with it!