Javascript Browser back button handling

tn500w_javascript-logo

Javascript Browser back button handling

In Javascript getting handle of browser back button event is complex. There are many plugIns available to satisfy this complex need. However, I cam across a solution which to some extent can resolve this issue.

if (window.history && window.history.pushState) {
  if(location.hash.split("#")[1]!='search'){
    	window.history.pushState('forward', null, '#search');
  }
}

This piece of code will first do a forward event in history and as an example I have inserted #search as the URL

So, by now if you load your page in browser, apart from the original URL corresponding to your page, there will be one more URL that gets stacked into the history <yourURL>#search

Now you need another piece of code that detects if the URL with #search is popped out of history stack, in another words back button is clicked.

if (window.history && window.history.pushState) {
    	$(window).on('popstate', function() {
      		var hashLocation = location.hash;
      		var hashSplit = hashLocation.split("#");
      		var hashName = hashSplit[1];

      	if (hashName !== '') {
        	var hash = window.location.hash;
        	if (hash === '') {
          		window.location.href = 'yourTargetURL';
        	}
      	}
    });
  }

You can put the above in a single if condition.

It would be good if you execute it when your page is loaded.

About Anoop Kumar Rai