62

EDIT-2: None of the answers seem to work. Not even the one I previously marked as the answer of this question. Any help is appreciated. Thanks.

First, I have googled for a how-to on creating a 'Go Back' link that allows the user to return to the previous page, and these are two ways of doing it:

<a href="javascript:history.go(-1)">[Go Back]</a>

and...

<a href="#" onclick="history.go(-1);return false;">[Go Back]</a>

Which of these two is a better choice? And why? (Also, please shed some light on browser compatibility.)

That's one half of the question. Now if mine is the first page the user is visiting, the 'Go Back' link wouldn't work, right? (As there's no pre-existing history for the window or tab.) In that case, I want the link to fallback and take the user to http://example.com.

i.e. if history exists, the user is taken to the previous page, and if it doesn't he's taken to http://example.com.

How do I do that? Hope someone can help.

EDIT: Please note that I do not know JavaScript, so kindly make your answer explanative. Thanks.

its_me
  • 10,998
  • 25
  • 82
  • 130
  • possible duplicate http://stackoverflow.com/questions/3588315/how-to-check-if-the-user-can-go-back-in-browser-history-or-not – ajax333221 Mar 18 '12 at 05:25
  • @ajax333221 - With all due respect — it's not. It's obvious if you read my question completely. – its_me Mar 18 '12 at 05:29
  • the problem is that you asked multiple things. But from the horizontal line to below, the dup will do exactly what you are looking for – ajax333221 Mar 18 '12 at 05:37
  • @ajax333221 I didn't just ask for a go-back link, I also wanted it to redirect to a link if no history exists. – its_me Mar 18 '12 at 05:38
  • "I didn't just ask for a go-back link", well if actually read the dup, you will see they address the other issue as well – ajax333221 Mar 18 '12 at 05:42

12 Answers12

32

You cannot check window.history.length as it contains the amount of pages in you visited in total in a given session:

window.history.length (Integer)

Read-only. Returns the number of elements in the session history, including the currently loaded page. For example, for a page loaded in a new tab this property returns 1. Cite 1

Lets say a user visits your page, clicks on some links and goes back:

www.mysite.com/index.html <-- first page and now current page                  <----+
www.mysite.com/about.html                                                           |
www.mysite.com/about.html#privacy                                                   | 
www.mysite.com/terms.html <-- user uses backbutton or your provided solution to go back

Now window.history.length is 4. You cannot traverse through the history items due to security reasons. Otherwise on could could read the user's history and get his online banking session id or other sensitive information.

You can set a timeout, that will enable you to act if the previous page isn't loaded in a given time. However, if the user has a slow Internet connection and the timeout is to short, this method will redirect him to your default location all the time:

window.goBack = function (e){
    var defaultLocation = "http://www.mysite.com";
    var oldHash = window.location.hash;

    history.back(); // Try to go back

    var newHash = window.location.hash;

    /* If the previous page hasn't been loaded in a given time (in this case
    * 1000ms) the user is redirected to the default location given above.
    * This enables you to redirect the user to another page.
    *
    * However, you should check whether there was a referrer to the current
    * site. This is a good indicator for a previous entry in the history
    * session.
    *
    * Also you should check whether the old location differs only in the hash,
    * e.g. /index.html#top --> /index.html# shouldn't redirect to the default
    * location.
    */

    if(
        newHash === oldHash &&
        (typeof(document.referrer) !== "string" || document.referrer  === "")
    ){
        window.setTimeout(function(){
            // redirect to default location
            window.location.href = defaultLocation;
        },1000); // set timeout in ms
    }
    if(e){
        if(e.preventDefault)
            e.preventDefault();
        if(e.preventPropagation)
            e.preventPropagation();
    }
    return false; // stop event propagation and browser default event
}
<span class="goback" onclick="goBack();">Go back!</span>

Note that typeof(document.referrer) !== "string" is important, as browser vendors can disable the referrer due to security reasons (session hashes, custom GET URLs). But if we detect a referrer and it's empty, it's probaly save to say that there's no previous page (see note below). Still there could be some strange browser quirk going on, so it's safer to use the timeout than to use a simple redirection.

EDIT: Don't use <a href='#'>...</a>, as this will add another entry to the session history. It's better to use a <span> or some other element. Note that typeof document.referrer is always "string" and not empty if your page is inside of a (i)frame.

See also:

Community
  • 1
  • 1
Zeta
  • 103,620
  • 13
  • 194
  • 236
  • 1
    Can you be a bit more clear about the comment — If the previous page starts to load or fully loads in a given time? – its_me Mar 18 '12 at 10:48
  • Well, it's more "if the current page hasn't been unloaded in a given time". Whenever your browser leaves the page. – Zeta Mar 18 '12 at 11:02
  • This is the only thing that seems to be working, how sad, there's not one straight forward way. – its_me Mar 18 '12 at 11:41
  • Well, you could check whether the `history.length` is `1` and add a `window.location.hash = 'intropage'`. Then you could check whether your current hash is `intropage`. However, as you said, there's no straight forward way. And don't forget that this solution won't work if JavaScript is deactivated. – Zeta Mar 18 '12 at 11:45
  • @Pacerier: So, when `window.goBack` gets used, it uses `history.back()`, which will leave the current context. If this happens _before_ the timeout expires (set in `setTimeout`), the user will happily go back in the history. If it _doesn't_ happen during those 1000ms, `window.location.href = ...` will redirect the user to a default page. Note that it's been three years since I've answered this question. I don't have time at the moment, but I can probably create an image which makes this a little bit more clear. – Zeta Apr 06 '15 at 07:36
  • @Zeta, Ok I get the *hack* now. But this seems to be a very limited solution. For example, we couldn't do something like check if there's any "back history" left and hide the Back button altogether. – Pacerier Apr 07 '15 at 12:48
  • @Pacerier: Yes it's limited. So? It's, as you say, _a hack_. Unfortunately, current browsers and the HTML5 history API don't provide the necessary means to accomplish OP's original request. – Zeta Apr 07 '15 at 12:53
  • 1
    @Zeta, Hopefully we can do it next time. 74k views to this page... people sure want this feature. – Pacerier Apr 11 '15 at 14:17
15

check window.history.length or simply, history.length

EDIT: some browsers start their history with 0, others with 1. adjust accordingly.

if it has a value of 1, it means it's the first page in that window/tab - then you can have JS redirect you.

<script>
    function backAway(){
        //if it was the first page
        if(history.length === 1){
            window.location = "http://www.mysite.com/"
        } else {
            history.back();
        }
    }
</script>

<a href="#" onClick="backAway()">Back</a>
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • 1
    I do not know JavaScript, can you kindly provide me the actual code? Thanks. – its_me Mar 18 '12 at 05:19
  • are you sure you need to check against `1`?, I think it is to `0` – ajax333221 Mar 18 '12 at 05:24
  • MDN says a newly loaded page has a history.length of 1, check the link in the post – Joseph Mar 18 '12 at 05:26
  • Something's probably wrong. It doesn't seem to work. Doesn't even show the link. :( – its_me Mar 18 '12 at 05:27
  • @Joseph : I'm sorry. It's my fault. Your code is working 100%. Thanks a lot :) – its_me Mar 18 '12 at 05:31
  • starting values vary by browser. check the browser before applying. – Joseph Mar 18 '12 at 05:35
  • @Joseph But I want it to work properly on all browsers, at least IE8 and later. Any other way around? – its_me Mar 18 '12 at 05:42
  • then do object detection to know what browser the user is using, and evaluate the history accordingly http://www.quirksmode.org/js/support.html – Joseph Mar 18 '12 at 05:51
  • @Joseph : I have found a way, using referrers. Please take a look at ajax333221's answer: http://stackoverflow.com/a/9756201/1071413 – its_me Mar 18 '12 at 05:55
  • @Joseph : If you can, please approve my edit to ajax333221's answer. Thanks for trying to help. :) – its_me Mar 18 '12 at 05:58
  • @JosephtheDreamer, **This will not work**. It could say 10 if you have "foward" entries, even while the backward entries are 0. – Pacerier Apr 06 '15 at 07:25
12

both would work the same, its just two different methods to call the same function. Try the following:

<a href="javascript:history.back();">[Go Back]</a>
spacebiker
  • 3,777
  • 4
  • 30
  • 49
  • Please take a look at my question again. I also want the link to take users to http://example.com if no history exists for the tab or window. – its_me Mar 18 '12 at 05:22
  • Are you sure it's correct? It doesn't seem to be working. I get this error — `This webpage is not found No webpage was found for the web address: file:///C:/Users/xxx/Desktop/New%20folder/history.length%3E0?javascript:history.back():%20window.location%20=%20'http://www.mysite.com/';` Please check. Thanks. – its_me Mar 18 '12 at 05:33
  • ops sorry, like this: `[Go Back]` javascript: goes first to tell href js must be executed. – spacebiker Mar 18 '12 at 05:37
  • There's one issue with using `history.length` as different browser have different values. Chrome and Firefox for example, use `1`. Please see Joseph's comment: http://stackoverflow.com/a/9756193/1071413 – its_me Mar 18 '12 at 05:45
  • The following will check if it knows how to do the "referrer" method (safari, ff, crhome).. If not (IE) it uses 0 `[Go back]` – spacebiker Mar 18 '12 at 06:25
  • I would STRONGLY suggest putting the javascript code in the `onclick` attribute, so you can use the `href` attribute for the page you go to when no history exists. – Mr Lister Mar 18 '12 at 08:33
  • @MrLister : None of the answers seem to be working (I did not check properly earlier). If you know JavaScript, please do put a tested answer. – its_me Mar 18 '12 at 09:12
  • @badlearner, take a look at this post, it may help http://stackoverflow.com/questions/1873290/using-javascript-history-back-fails-in-safari-how-do-i-make-it-cross-browse – spacebiker Mar 18 '12 at 09:16
  • @CharasOverride Tried them all, no combination is working. :( – its_me Mar 18 '12 at 09:22
  • 1
    Damn, that is weird.. can you provide some info about your environment.. i.e: firefox under windows, etc.. ? – spacebiker Mar 18 '12 at 09:28
  • @badlearner OK, now what you should do is tell us exactly how you tested. Which operating system, which browser(s) and version number(s) etc. and what the exact results were (nothing; error; ended up on wrong page etc) – Mr Lister Mar 18 '12 at 09:29
  • @MrLister and CharasOverride : I am on Windows 7, using the latest version of Chrome (v17.0.963.79). I tried two code variants (here: http://pastebin.com/znh65cjQ) among many others, and what happens is — I am being taken to http://example.com no matter what. Even if browser history exists in current window, clicking the 'Go Back' link isn't taking me back to the previous page — it just takes me to http://example.com – its_me Mar 18 '12 at 09:41
  • @CharasOverride : Plz see my previous comment (right above). I've provided the details you asked for. – its_me Mar 18 '12 at 09:50
  • @CharasOverride Can you please use pastebin? (I don't know JS and the code in your comment appears to be broken — unformatted) – its_me Mar 18 '12 at 10:01
  • yep, i know.. i added a new answer – spacebiker Mar 18 '12 at 10:03
8
echo "<p><a href=\"javascript:history.go(-1)\" title=\"Return to previous page\">&laquo;Go back</a></p>";

Will go back one page.

echo "<p><a href=\"javascript:history.go(-2)\" title=\"Return to previous page\">&laquo;Go back</a></p>";

Will go back two pages.

Steve
  • 81
  • 1
  • 2
  • This worked for me, you can see it in action here. https://supfort.com/wrong, click Go Back at the top right corner or the button to the left from Send Message Again button. By the way I am using go two pages back, just in case you did not notice. And it only works when you fill the form and you either get the wrong page or the thank you page. https://supfort.com/thanks – lupoll88 Feb 10 '19 at 17:22
7

The reason on using the return:false; is well explained on this other question.

For the other issue, you can check for the referrer to see if it is empty:

    function backAway(){
        if (document.referrer == "") { //alternatively, window.history.length == 0
            window.location = "http://www.example.com";
        } else {
            history.back();
        }
    }

<a href="#" onClick="backAway()">Back Button Here.</a>
Community
  • 1
  • 1
ajax333221
  • 11,436
  • 16
  • 61
  • 95
  • I do not know JavaScript, can you kindly provide me the actual code? Thanks. – its_me Mar 18 '12 at 05:19
  • Thanks for the edit. I apologize — while I visited the dupe link, I didn't look at the second answer. Now it makes sense completely. I would like to edit your answer to make it complete for noobs (like me). – its_me Mar 18 '12 at 05:50
  • @badlearner I did another update, to answer other of your doubts – ajax333221 Mar 18 '12 at 05:53
  • My edit may have clashed with yours. :( Please see if you can approve my edit. Thanks. – its_me Mar 18 '12 at 05:54
  • But, there are two ways of doing it. I have the edit for your on pastebin: http://pastebin.com/EUuq9tH7 - - If you think it's okay, please add that to your answer. It will be a great reference for me. :) Thanks. – its_me Mar 18 '12 at 06:03
  • Maybe I didn't check properly before, but this doesn't seem to be working. Damn! This is getting tricky. – its_me Mar 18 '12 at 08:31
6

this seems to do the trick:

function goBackOrGoToUrl() {    

    window.history.back();
    window.location = "http://example.com";

}

Call history.back() and then change the location. If the browser is able to go back in history it won't be able to get to the next statement. If it's not able to go back, it'll go to the location specified.

xtrahelp.com
  • 926
  • 8
  • 14
3

The following code did the trick for me.

html:

<div class="back" onclick="goBackOrGoHome()">
  Back
</div>

js:

home_url = [YOUR BASE URL];

pathArray = document.referrer.split( '/' );
protocol = pathArray[0];
host = pathArray[2];

url_before = protocol + '//' + host;

url_now = window.location.protocol + "//" + window.location.host;


function goBackOrGoHome(){
  if ( url_before == url_now) {
    window.history.back();    
  }else{
    window.location = home_url;
  };
}

So, you use document.referrer to set the domain of the page you come from. Then you compare that with your current url using window.location.

If they are from the same domain, it means you are coming from your own site and you send them window.history.back(). If they are not the same, you are coming from somewhere else and you should redirect home or do whatever you like.

Alexis
  • 31
  • 1
  • 3
2

Added a new answer to display the code formatted:

The thing is that you were checking for document.referer, because you were in ff it was returning always true, then it was navigating to http://mysite.com. Try the following:

function backAway(){
    if (document.referrer) {
        //firefox, chrome, etc..
        i = 0;
    } else {
        // under ie
        i = 1;
    }
    if (history.length>i)
    {
        // there are items in history property
        history.back();
    } else {
        window.location = 'http://www.mysite.com/';
    }
    return false;
}
spacebiker
  • 3,777
  • 4
  • 30
  • 49
  • I just tested this on firefox, doesn't take me to http://www.mysite.com/ this time. It takes me to previous page if history exists though. So, only one thing is working, either that or this. – its_me Mar 18 '12 at 10:04
  • And in chrome, it's not working at all. And IE9 it says, IE has blocked this site from running scrips or accessing Active X controls. :( – its_me Mar 18 '12 at 10:09
  • im not sure about firefox setting history.length to 1, you will have to check, so try to modify `i = 1` for `i = 0` – spacebiker Mar 18 '12 at 10:09
  • no it is not.. it is trivial ! can you please make me a favour ? add the following on top and check the alert message when there is no history back `alert(history.length);` on any browser you can.. – spacebiker Mar 18 '12 at 10:17
  • `1` in latest versions of Firefox, Chrome, Safari, and Opera. `0` in Internet Explorer 9. – its_me Mar 18 '12 at 10:22
  • Unfortunately, it does not. Thanks a lot for your time, and trying to help. – its_me Mar 18 '12 at 10:46
  • i removed the comment because as soon as i wrote i realized that could not be the issue.. im stunned that did not work.. but yeah, unless i dont get the hands on it, its difficult. Anyway if you keep on testing use the alert command and/or firebug for debuggin, cheers – spacebiker Mar 18 '12 at 10:52
  • hey there! you should give a try to `self.window.location` instead. i had one issue with window.location not refering well to the page i requested and adding `self` solved my problem. – spacebiker Mar 19 '12 at 08:26
  • Did you give up?.. because i still got more ideas in the tophat – spacebiker Mar 19 '12 at 19:03
  • Share away! My computer crashed the other day, so I was unavailable. – its_me Mar 21 '12 at 05:27
  • You can go use jQuery libraries so that it takes care of your backlink, check this tut http://www.electricfairground.com/2009/10/01/restoring-conventional-page-navigation-to-your-javascript-application-with-jquery-history-plugin/ – spacebiker Mar 21 '12 at 11:06
  • I understood bits and pieces of the tut, but I don;t want to do any mistakes (I do not know JavaScript). It would be great if you can put that into an answer (or modify this answer perhaps?). Thanks. – its_me Mar 21 '12 at 12:56
  • Reading my last answer today, with my head properly awake, i realized there was a bug in the code. So, please give this a try before going further. The explanation is very simple. Safari, Chrome, etc.. use 0 as history.length, ie uses 1. In my previous answer i just wrote that if it was Safari use 1 where it had to use 0, and the other way around. Give a try to my recently modified answer, copy it as it is because i have already reedited. – spacebiker Mar 22 '12 at 02:51
  • This is weird. It worked the first time I tried in Chrome. Upon repeated tests, the link does nothing! (It also worked on Firefox - I don't have my windows laptop around to test Safari and IE.) – its_me Mar 22 '12 at 04:17
  • ok, at least there was some progress. Check it out in other browsers and report. You can use `alert(document.referrer);` to check wether a condition is working or not. – spacebiker Mar 22 '12 at 23:16
1

simply use cookies to store your visited page list.

and apply some if else.

EDIT: also use ServerVariables HTTP_REFERER.

MRRaja
  • 1,073
  • 12
  • 25
  • Using server variables as an alternative might be good most of the time to eliminate cross browser issues. – Jonats Jan 06 '15 at 06:20
1

You need to check both document.referrer and history.length like in my answer to similar question here: https://stackoverflow.com/a/36645802/1145274

Community
  • 1
  • 1
gregmatys
  • 2,151
  • 18
  • 19
0

How about using the history replacement function to add the site into the browsers history?

Try executing the following as soon as the window loads-

history.replaceState("example", "title", "http://www.example.com");

This should hopefully make it so even if it is the first page they have accessed, the URL you define in the code will be what they're taken to when they click back.

Muhan Alim
  • 479
  • 1
  • 7
  • 17
0

You should use window variable - window.referrer. This variable contains the last page the user visited if they got to the current page by clicking a link For example:

  function goBack() {
    if(document.referrer) {
      window.location.href = document.referrer;

      return;
    } 

    window.location.pathname = '/';
  }

This code redirect user to previous page if this is exist and redirect user to homepage if there isn't previous url

vladpopovv
  • 121
  • 3