37

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?

4
  • 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. Commented Nov 8, 2011 at 6:55
  • That's true... Just came across some posts about the HTTP_REFERRER parameter. Hence was wondering if it is possible. Thanks! Commented Nov 8, 2011 at 7: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. Commented Nov 8, 2011 at 7:10
  • Please don't edit the solution into the question. Post it as an answer. Thanks. Commented Jan 8, 2024 at 21:56

1 Answer 1

64

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.

Sign up to request clarification or add additional context in comments.

4 Comments

@Alan - please don't reference W3Schools for things like window.history, use MDN, W3C or applicable standards wherever possible. And also use fully qualified references (i.e. window.history, not just history).
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 6 years later, anchor tags ned to have a valid href. If there is no href, use a button instead.
@RobG 11 years later...W3Schools has improved their content and is a solid source for web development information.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.