16

Is it possible check if there is a value for history.go(-1)? I know you can't access history.previous directly.

I am trying to stay away from document.referrer because I know it can be blocked in some instances.

Here is what I am trying to do. I have an error page, on this page I would like to either have a BACK button (if it's not the only item in history) or a close button (if it is).

Louis W
  • 3,166
  • 6
  • 46
  • 76
  • Possible duplicate of [How to check if the user can go back in browser history or not](http://stackoverflow.com/questions/3588315/how-to-check-if-the-user-can-go-back-in-browser-history-or-not) – bummi Jan 22 '16 at 06:50

5 Answers5

18
if (history.length) {
    //There is history to go back to
    history.go(-1);
}    
Andreas Grech
  • 105,982
  • 98
  • 297
  • 360
15

Actually, history.length is always one or more, since the current page counts. Also, if you have a forward history (i.e. you used the back button), those pages also count. So you need a more complicated check:

if( (1 < history.length) && document.referrer ) {
4

There is no cross-browser approach to accomplish this. Document.Referrer may be set even if no history entry exists.

I came up with the following "hack". It utilizes the onbeforeunload event to detect whether the browser starts leaving the page or not. If it does not in a certain timespan it'll just redirect to the fallback.

window.goBack = function goBack(fallback){
  var useFallback = true;
  window.onbeforeunload = function(){
    useFallback = false;
  }
  window.history.back();

  setTimeout(function(){
    if (useFallback){ window.location.href = fallback; }
  }, 100); 
}

You can call this function using goBack("fallback.example.org").

One of the use cases is that you may want to add a back button to any page and also want to make sure that this back button works even if the user goes directly to this page (e.g. by bookmark, direct link etc).

So either it does perform a history.back() or if there is no entry, it'll redirect to a fallback.

posixpascal
  • 3,031
  • 3
  • 25
  • 44
1

If the history has a length greater than 0, then it contains at least one history point.

if (history.length)
Ian Elliott
  • 7,588
  • 5
  • 35
  • 42
-1
 function test() {
        document.URL = document.referrer;            
    }
soheil bijavar
  • 1,213
  • 2
  • 10
  • 18