Manipulating browser URL using Javascript without refreshing the page

In modern browsers, one of the most interesting feature is that you can change the browser url without refreshing the page. During this process you can store the state of the history so that you can pull the necessary data when someone hits the back-button in the browser and then take necessary action based on that. It’s not as complicated as it may sound now. Let’s write some code to see how it works.

var stateObject = {};
var title = "Wow Title";
var newUrl = "/my/awesome/url";
history.pushState(stateObject,title,newUrl);

History objects pushState() method takes three parameter as you can see in the above example. First one, a json object, is very important. Because this is where you will be storing arbitrary data related to the current url. Second parameter will be the title of the document, and third one is the new url. You will see your browser’s address bar is updated with the new url, but the page was not refreshed :)

Let’s see another example where we will be storing some arbitrary data against each url.

for(i=0;i<5;i++){
  var stateObject = {id: i};
  var title = "Wow Title "+i;
  var newUrl = "/my/awesome/url/"+i;
  history.pushState(stateObject,title,newUrl);
}

Now run and hit the browser back button to see how the url is being changed. For each time the url is changed, it is storing a history state object with the value “id”. But how can retrieve the history state and do something based on that. We need to add an event listener for “popstate” event which is fired everytime the history object’s state is changed.

for(i=0;i<5;i++){
  var stateObject = {id: i};
  var title = "Wow Title "+i;
  var newUrl = "/my/awesome/url/"+i;
  history.pushState(stateObject,title,newUrl);
  alert(i);
}

window.addEventListener('popstate', function(event) {
  readState(event.state);
});

function readState(data){
  alert(data.id);
}

Now you can see whenever you hit the back button, a “popstate” event is fired. Our event listener then retrieves the history state object which was associated with that url and prompt the value of “id”.

It’s easy and pretty interesting, eh?

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s