Manipulating the Web History Using HTML5 API
As we know that web applications have been evolved dynamically and JavaScript has been using increasingly to dynamically load content into web pages. Earlier, web developers couldn’t do much about with the browser history especially when it comes to manipulating it and preserving an accurate information for the users benefit. Although, they could push users backward and forward, but it wasn’t that useful. With the prominence of more solid web pages, developers demand more control. Thanks to HTML5, which provides goodies to the webmasters by providing better control with the form of extending the JavaScript History API.
In this tutorial, you are going to learn about how to tame browser history by using JavaScript along with understanding the URL formatting.
1. Create an In-built Support for the History API
For grabbing the browser history, first of all, you need to attach some JavaScript with the universal jQuery handler. This will help try your hands with the rest of the coding process where you can effectively organize all the historical elements. Make sure not to completely execute your library until the page is fully loaded. After this,
- Open the _Layout.cshtml file which resides under the shared folder and start removing the script tags placed on the jQuert and Modernizer scripts.
- Now, replace them with the latest libraries located on the Microsoft CDN.
For a better understanding, look at the tags located on _Layout.cshtml file.
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22http%3A%2F%2Fajax.aspnetcdn.com%2Fajax%2FjQuery%2Fjquery-1.7.1.js%22%20type%3D%22text%2Fjavascript%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>" /> <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22http%3A%2F%2Fajax.aspnetcdn.com%2Fajax%2Fmodernizr%2Fmodernizr-2.0.6-development-only.js%22%20type%3D%22text%2Fjavascript%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>" />
Now, at this point you need to add a new JavaScript file to your application and name it as main.js. We recommend you to provide a referance with this file before finally closing _Layout.cshtml page. MVC URL helper is a function which can be used to ensure the accurateness of the path when the application is used.
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20src%3D%22%40Url.Content(%22~%2FScripts%2Fmain.js%22)%22%20type%3D%22text%2Fjavascript%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="<script>" title="<script>" />
Now, open the main.js file and add the jQuery handler. It should look like this:
$(document).ready(function () { if (!Modernizr.history) return; });
2. Tying the Browser History Event
In this step, you need to connect the historical events of the browser. Browsers supporting history API generally have onpopstate historical events available for wiring up. This can be done in two ways: 1) with JavaScript event, 2) jQuery Bind Function.
onpopstate = function (event) { function body }; $(window).bind("popstate", function (event) { functin body }); now, add the following code to execute the onpopstate function if the event is fired in the browser window. $(window).bind("popstate", function (event) { updateState(history.state); });
3. Manipulating The History Directly
Up to this point, you have gained a clear understanding of the events that fires with the history objects. Now at this stage, we are going to tell you about two more logical elements that help you have a better grasp of the concept. First of all, the links on the menu page serve as the actual anchor tags that will enable browser to completely scan the server to get the entire page. Secondly, whenever you obtain the value from the history.state property, you just can’t assign a value randomly unless until to you don’t implement your updateState function.
Generally, history objects consist of two functions that help in the direct manipulation of the history stack. They are- pushState and replaceState. The main function of pushState to to add new elements to the history stack of the browser that has been running currently. ReplaceState is used for taking the entry of current historical event and replaces the values of data, link, and URL without adding or removing the history stack.
4. Working with the Page URL in JavaScript
The window object in JavaScript comes with a location property which goes beyond simply functioning like a URL, which you see in the address bar of the browser. It is, in fact, a mixture of all the major components of the current URL along with method called reload that compels a page to re-request everything from the server of the present web page. These multiple properties are generally small elements of the URL which can be presented in the form of strings, which could be parsed and divided further as and when required.
Up to this point, it should be clear what purpose we are trying to achieve. In order to create an object that includes everything you need for your movie hub (taking it as an example), take a typical URL to be used in your application.
http://www.xyzwebsite.com/Movies/Songs/Old
Now, divide the location.pathname to build a complete JavaScript object.
function stateFromPath(path) { var base = "/Movies/"; var parts = path.replace(base, "").split("/"); #A return { #B meal: (parts.length >= 1 ? parts[0] : ""), #B dish: (parts.length >= 2 ? parts[1] : "") #B }; }
#A Removes the /Movies/ part of the path parameter and split the remaining string into an array.
#B The last part of the array should be the movies while the previous part is the movie hub element
The code written above has been given just for a referance. In the real scenario, you are adviced to test the URL to ensure its validity as per the business standards or whether the properties has been designed in an accurate order or not. Also, you could consider parsing out any of the querystring values and special characters to overcome the URL text encoding problems.
5. Applying History Lessons for Updating Pages
The step involves building the updateState function and evaluating its performance. This function goes directly to your main.js file and makes optimum use of jQuery selectors and Ajax server call for data previewing. The below mentioned code help you understand how state parameters could be assigned.
function updateState(state) { if (!state) state = stateFromPath(location.pathname); #A }
#A If the state value was not passed in, get it from the stateFromPath function
The previous snippet is provided just to ensure that you’ll be always provided with an accurate state value no matter whether there is any value existed when the onpopstate
function fires.
Now, perform some editing to the interface to improve the updateState function. The editing functions will be presented by default if the MVC function has been directly called with the running URL. To do this, add and then remove the CSS classes from the elements of the same page. And run the code for updating the function accordingly.
var $selectedMenu = $(".movies[data-movie hub='" + state.moviehub + "']"); #A $(".movies").not($selectedMovies).removeClass("active"); #B $selectedMovies.addClass("active"); #C var $selectedItem = #D $(".movies-item[data-songs='" + state.songs + "']"); $(".movies-item").not($selectedItem).removeClass("selected"); $selectedItem.addClass("selected");
#A Gets the data attribute for the selected movie hub item.
#B Removes the active class from every other movies item.
#C Adds the active class to the selected movie hub item.
#D Performs the same actions against the movie items.
Conclusion
So there we have it all, use this tutorial for manipulating your web history and enahnce your presentation and browsing experience.