Skip to content Skip to sidebar Skip to footer

History.back() - How To Set A Default If No History Exists

I'm trying to be clever and considerate towards users, but once again, I've run into a 'design' issue. I have a number of pages on a website where I've chosen to remove the default

Solution 1:

Set the href to the specific URL, then use javascript to override this behaviour if a history record exists.

<a id="backbtn" href="/specific/url">Back</a>

document.getElementById("backbtn").addEventListener("click", function(){
    if (history.length){
        history.back();
        returnfalse;
    }
});

http://jsfiddle.net/d1gz8ue9/8/

That way your link is still valid without javascript and can be opened in a new window.

Solution 2:

Well, you can always try the 'bad' practise in the eyes of some, of overwiting hte native function with your own if the history is empty. Thats the quick and dirty if your code relies on auto generated code that implements history.back.

if(!history.length) {
  history.back = function(){location.href='mydefaultpage';};
  }

But if I were you, i'd just make my own personalised back function that checks the length of history like curt has shown in his answer.

Also for your back button I would forgo the

href="javascript:history.back()"

and replace it with

href="#"onclick="!history.length?location.href='foobar.html':history.back()"

or define it in a function

<a href="#"class="back-button">

(function(){ 
    var leave = function() {
        !history.length ? location.href='foobar.html' : history.back();
    };
    var arr = document.getElementsByClassName('back-button');
    for(var i=0;i<arr.length;++i) {
            arr[i].addEventListener('click',leave);
        }
    }
})();

Solution 3:

I know it's an old question but i had to solve the problem recently and needed it to work with windows opened with a _blank target in the opener link (in this case the history.length is already 1 and not 0), and I came up with this:

if (history.length > 1) {
  if (history.back() === undefined) {
    history.pushState({}, '', defaultRouteUrl);
  }
} else {
  history.pushState({}, '', defaultRouteUrl);
}

Basically if there is a history it tries to go back, but if something went wrong then navigate to the defaultRouteUrl

For more infos refer to: https://developer.mozilla.org/en-US/docs/Web/API/History

Post a Comment for "History.back() - How To Set A Default If No History Exists"