34

I want to trigger the browser's back functionality through a hyperlink in my page template, using JavaScript (or PHP if possible). Does anyone know how to implement this?

EDIT
Found the solution using JavaScript. Here is the link if anyone needs it.
And here's the code:

<a href="#" onclick="history.back();return false;">Go back</a>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Rutwick Gangurde
  • 4,772
  • 11
  • 53
  • 87
  • You can't use PHP for that because it is a server-side language and the browser is on the client side. So you wouldn't have access to the browser's history. – Thunraz Nov 08 '11 at 06:55
  • That's true... Just came across some posts about the `HTTP_REFERRER` parameter. Hence was wondering if it is possible. Thanks! – Rutwick Gangurde Nov 08 '11 at 07:04
  • Right. I didn't think of that. You _could_ echo the contents of `HTTP_REFERER` into a link, but it's not guaranteed that it is set. For example some anti virus software/firewalls remove the referer. Or the user somehow got on your page using a meta refresh. Some browsers remove the referer there as well. But going with JavaScript's `history.back()` function is probably safer. – Thunraz Nov 08 '11 at 07:10

1 Answers1

61

history.back() should do the trick.

window.history.back() documentation at MDN

As an aside, it's bad user experience if you do this unexpectedly on the user. For example, I enter in an invalid credit card number, and you take me back one page, instead of letting me fix the mistake.

So while it's possible to use javascript to manipulate the history stack, it's better to only do so if it makes sense in the context current users actions.

georgephillips
  • 3,540
  • 4
  • 23
  • 30
Alan
  • 45,915
  • 17
  • 113
  • 134
  • @RutwickGangurde Thanks, but it doesn't look like you actually accepted the answer. – Alan Nov 08 '11 at 07:01
  • Yes I know... still 2 more minutes to go before I'm allowed to accept the answer! – Rutwick Gangurde Nov 08 '11 at 07:02
  • 4
    @Alan - please don't reference [W3Schools](http://w3fools.com/) for things like [window.history](https://developer.mozilla.org/en/DOM/window.history), use MDN, W3C or applicable standards wherever possible. And also use fully qualified references (i.e. `window.history`, not just `history`). – RobG Nov 08 '11 at 07:07
  • @RobG Thanks for the links. I did not know! – Alan Nov 08 '11 at 17:05
  • This worked for me as well. However, just a note, that in Chrome if I also had a href="#" attribute set, then it did not work. The presence of the same in Firefox was not a problem. – fraxture Sep 16 '14 at 21:05
  • @fraxture 6 years later, anchor tags ned to have a valid href. If there is no href, use a button instead. – Alan Feb 10 '20 at 20:41
  • 3
    @RobG 11 years later...W3Schools has improved their content and is a solid source for web development information. – Alan Feb 21 '22 at 21:19