HTML5

HTML5 History API Example

Pre HTML5 we could only perform few basic operations on the browser history stack, simple operations like re-visiting a previously visited URL. Today (with HTML5) we can perform more complex operations on the browser history stack.
 
In this example we are going to develop simple modules that work with the new features added to HTML5 history API.
 
 
 
 
 


 
For this example we will use:

  • A computer with a modern browser installed.
  • Notepad++.

1. Getting Started

Every time a browser visits a new URL, it records or stores the URL (some browsers implementation store the URL in a local SQL database, if the browser is shut down and restarted again the user history is still available). An exception to this is when the user is surfing the web in incognito mode(the history is not stored permanently)In that case once the tab is deleted, its history is also deleted.
 
For example a user visits “google.com” then google.com is stored in the browser history record, as the latest record- on top of the stack. If the user then visits Microsoft.com and later webcodegeeks.com. The stack will look something like what is seen below:

http://www.webcodegeeks.com
http://www.microsoft.com
http://www.google.com

The browser pointer would be at the latest record(webcodegeeks). A go back operation will cause the pointer to move to the second URL in the list(Microsoft) and the URL is loaded either from the browser cache or the server. If the browser pointer is at webcodegeeks.com, a go forward operation is ignored because webcodegeeks.com is the first or latest record.

1.1 Security Restrictions

For good reasons their are restrictions placed on the history API, these restrictions reduce the chances of a user being scammed by a malicious website. The HTML5 history API only gives a web page access to the part of the browsing history which lies within the same domain as the web page itself. With this restriction in place, a web page cannot see or edit other websites a user has visited.

Similarly the HTML5 history API does not allow a web page to push URLs onto the history stack(we would learn how to do this in a later section) which are outside the same domain as the domain of the web page. This restriction ensures that a web page cannot pretend to have forwarded the user to another website.

1.2 Old History API

In this section we are going to look at the methods available to the early history API(before html5). These methods can be accessed through the history object, and the latter can be accessed through the window object. The history object has a property length, which returns the number of URLS in the history list.
The methods available to the history objects are:

  • back: When this method is called, it loads the previous URL in the history list.
    window.history.back();
    
    

    It functions as if the user clicked the back button on the browser interface.

  • forward:When this method is called, it loads the next URL in the history list.
    window.history.forward();
    

    It functions as if the user clicked the forward button on the browser interface.

  • go: It loads a specific URL from the history list, which is relative to the pointer current position in the history list.
    window.history.go(1);//goes one steps forward
    window.history.go(2);//goes two steps forward
    window.history.go(-1);//goes one step backward
    
    window.history.go(-2);//goes two step backward
    

Since the window object is the default object you can leave it out. A user cannot move forward in history unless the user has first moved back in history.
Lets look at a complete example below:

index.html

<!DOCTYPE html> 
<html lang=en>
	<head>
	<style>
	html, body{
	width:100%;
	height:100%;
	margin:0%;
	font-family:"helvetica","verdana","calibri", "san serif";
	overflow:visible;
	padding:0%;
	border:0%;
	}
#pick{
margin:10px;
}
	</style>
	 		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi"/>
	
	<title> 
Html5 History API Example
</title>

	</head>
	<body onload=init()>
<script>
function init(){
var b=document.getElementById("back")
//get the back button 
b.addEventListener("click",goback,false);//register an onclick event listener
var f=document.getElementById("forward")
//get the forward button 
f.addEventListener("click",goforward,false);//register an onclick event listener
var b=document.getElementById("go")
//get the go button 
b.addEventListener("click",gos,false);//register an onclick event listener
}
function goback(){
window.history.back();//call the history method go back
console.log("going back")//print out message

}
function goforward(){
window.history.forward();//call the history method go forward
console.log("going forward")//print out message

}
function gos(){
var d=document.getElementById("tex")
var d1=d.value;
if(d1=="")
console.error("Wrong Value Specified");//no valid input was found, print out error message
else
window.history.go(d1);
console.log("going to a specified position");// print out message

}
</script>
<p>
<p>
<input type = button id = back value=back>
</p>
<p>
<input type = button id = forward value=forward>
</p>
<p>
<label>Enter a valid step number</label>
<input type = text id = tex >
<input type = button id = go value=go>
</p>
</p>

	</body>
	</html>

We add three buttons and a textbox to the user interface. Click the button labelled back to go back, click the button labelled forward to go forward, enter a valid number in the textbox and click go to move to a specific URL.
 
Note The script doesn’t check for illegal values like letters. So make sure you enter a valid number e.g 1, 2, -1, -2. This example works best when your browser/tab actually has a history length greater than 0.
 
Note: Inline JavaScript should be avoided because it makes the markup bigger and less readable. The content, structure and behavior are not well-separated, thus making a bug harder to find. Furthermore, usage of event attributes almost always causes scripts to expose global functions on the Window object, thus polluting the global namespace.

1.3 New API

The new API were added in HTML5. The methods we can work with are:

  • pushState(): This method pushes a state to the history stack or list. A simple example below
    var stateobj = {}; 
    var title = ""; 
    var url = "index.html";
    history.pushState(stateobj, title, url);
    
    

    This will cause the URL bar to display the full URL, but the browser won’t load the URL or even check if it exists. Suppose the user now navigates to http://google.com, then clicks back. At this point, the URL bar will display http://someexample/index.html. The push state function takes three parameters:
    state object: is simply a JavaScript object. Whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry’s state object.

    title:A string value. It is currently ignored my some browsers.

    URL: The URL to be added to the history stack. It doesn’t need to be absolute, it can be a relative URL. The new URL must be of the same origin as the current URL else an exception is thrown. It is an optional parameter, if it is not provided, the current URL is assumed.

  • replaceState(): The replaceState() function replaces the history element in the history stack that is being pointed to right now. This may not be the top element if the user has moved back in history using the “back” button.
    This will also change the URL in the browser’s address field though it will not make the browser load the URL. The page that replaced the URL remains loaded in the browser.

    var stateobj = {}; 
    var title = ""; 
    var url = "index.html";
    history.replaceState(stateobj, title, url);
    
    

1.4 pop state event

A pop state event is fired every time the history entry changes. pushState() andreplaceState() both fire this event and their state object is contained as part of the event property.

window.onpopstate = function(event) { console.log("history has changed to: " + document.location.href);//we create a log message.

 }

It is possible to read the state of the current history entry without waiting for a popstate event.

var newstate = history.state;

2. Summary

In this example we learnt about the history object and its methods, we also studied about its restrictions.

3. Download the Source Code

Download
You can download the full source code of this example here: html5historyapiexample

Olayemi Odunayo

I am a programmer and web developer, who has experience in developing websites and writing desktop and mobile applications. I have worked with both schematic and schemaless databases. I am also familiar with third party API and working with cloud servers. I do programming on the client side with Java, JavaScript, html, Ajax and CSS while I use PHP for server side programming.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button