Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger browser's back event/function using JavaScript?

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>
like image 902
Rutwick Gangurde Avatar asked Nov 08 '11 06:11

Rutwick Gangurde


People also ask

How do you trigger a function in JavaScript?

onchange: It is triggered when an HTML element changes. onclick: It is triggered when an HTML element is clicked. onmouseover: It is triggered when the mouse is moved over a HTML element. onmouseout: It is triggered when the mouse is moved out of a HTML element.

How do I go back to previous page in JavaScript?

The history. back() method loads the previous URL (page) in the history list. The history. back() method only works if a previous page exists.

What event is fired when the back button of a browser is pressed?

The popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history. back() or history. forward() in JavaScript). Browsers tend to handle the popstate event differently on page load.


1 Answers

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.

like image 118
Alan Avatar answered Oct 14 '22 09:10

Alan