0

I've been using a back button for users to navigate back to the page they came from, problem is, if the user navigates there in a new tab or direct link, as they haven't "been anywhere" before they would get redirected back to a blank page.

Is there a solution for this? I'm thinking something like navigate back if possible, and if not it'll take you to a specific url.

This is what I have so far:

<a href="#" onclick="history.go(-1);return false;">Go back</a>
Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
kallekillen
  • 74
  • 1
  • 11
  • 1
    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) – Tchoupi Feb 12 '13 at 16:10
  • Personally, I think providing a message saying you can't go back would suffice. That's just my opinion. After the code part, this might go well on http://ux.stackexchange.com/ and ask what is preferred. – SchautDollar Feb 12 '13 at 16:12
  • Apologies about duplicate, have flagged for removal – kallekillen Feb 12 '13 at 16:38

2 Answers2

2

How about using document.referrer?
It's a hack and I do not recommend it since you'll not be maintaining post data (if any). If your page doesn't need to repost any data, then this should work.

<a id="mylink" href="#">Go back</a>
$('#mylink').click(function () {
    if (history.length == 0) {
        document.location = document.referrer;
    } else {
        history.go(-1);
    }
});

I must say that I agree with SchautDollar's comment - a message is a far better warning.

Community
  • 1
  • 1
Codesleuth
  • 10,321
  • 8
  • 51
  • 71
  • I tested this in Chrome when opening a new tab (middle click a link) and it kept the referrer. I'm not sure how standard this is though, there may be differences between browsers. – Codesleuth Feb 12 '13 at 16:27
0

If you are using php you could change link to:

echo '<a href="'. $_SERVER['HTTP_REFERER'] . '">Go back</a>';

if not you can do the same with jQuery and javascript

document.location = document.referrer;

on the link click method.

Vuk Vasić
  • 1,398
  • 10
  • 27