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?
1 Answer
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.
4 Comments
RobG
@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).fraxture
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.
Alan
@fraxture 6 years later, anchor tags ned to have a valid href. If there is no href, use a button instead.
Alan
@RobG 11 years later...W3Schools has improved their content and is a solid source for web development information.
HTTP_REFERRERparameter. Hence was wondering if it is possible. Thanks!HTTP_REFERERinto 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'shistory.back()function is probably safer.