Catching browser back

Today we searched for a solution to catch the browser back button.

The problem is, that the browser per default has no way to catch the back and forward actions. Also the browser does not allow to modify the browser history.

But there are two things you can do:

  1. call location.replace to load a diffrent url and replace the history of the current page.
  2. add a hash (like its used for anchor links) to the url with location.hash='hash'

Basically the idea was to add a hash when the page is loaded. When the user then clicks the browser back button, the url just changes back to the url without the hash. Then all you need to do is to detect that url change and react like you want (e.g. set a new location.href)

Here is the example



var lastjavascripthash='';

//if the current url has a hash on dom ready - than the user loads this url directly in browser
if (location.hash) {
alert('you navigated to this link using the browser address!');
//just add a dummy hash:

//optional - when clicking the links append the hash to the url:
$('#tostep1').click(function() {

//do regular check if the hash in the location still fits the last hash that was set via a valid javascript call
// if not it means someone else modified the hash - typically the browser back
setInterval(function() {
if (location.hash != lastjavascripthash) {
alert('you navigated to this link using the browser back!');
}, 300);

Since the loaction.hash declaration is not interpreted by all browsers, a better way is to use one of the history javascript plugins.

This is the case in this modified example
(using jquery.history.js Links:;

var browserback = {
lastjavascripthash: '',

setLastHash: function(hash) {
historyChangeHandler: function(hash) {
if (browserback.lastjavascripthash != hash) {
alert('you propably used browser back!');

disableBrowserBack: function() {
var hash=new Date().getTime()+ Math.floor(Math.random()*1000)


blog comments powered by Disqus