Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

webkit / Chrome history.back(-1) onclick vs href

Everybody knows that but I'll repeat the problem:

<a href="#" onClick="history.go(-1)">Back</a>

Will not work in WebKit based browsers (Chrome, Safari, Mxthon, etc.)

Another approach (should work) that won't work is:

<a href="#" onclick="javascript:window.history.back(-1);">Back</a>

You could do this - works! (but that's showing JS in url hint)

<a href="javascript:window.history.back(-1);">Back</a>

To use JS in onclick event you could do this (works, but see comments below):

<a onclick="javascript:window.history.back(-1);">Please try again</a>

Missing href will make it work, but then it won't appear as clickable link, you could apply css to make it look like link, apply blue color, underline and cursor hand, but who wants that?

like image 681
Pawel Cioch Avatar asked Feb 11 '13 15:02

Pawel Cioch


People also ask

What is history Go (- 1?

The History. back() method causes the browser to move back one page in the session history. It has the same effect as calling history.go(-1) . If there is no previous page, this method call does nothing.

How do you go one step back in Javascript?

back() method: The back() method of the window. history object is used to go back to the previous page in the current session history. In case there is no previous page, this method call does nothing. The onclick event can be specified with this method to go back one page in history.


2 Answers

Finally working solution, tested in IE, FF, Safari, Chrome, Opera, Maxthon:

<a href="#" onclick="window.history.back();return false;">Back</a>

Don't forget semicolon after return false;

like image 83
Pawel Cioch Avatar answered Oct 20 '22 18:10

Pawel Cioch


It works even history.go(-1) also...

For Chrome, IE, Mozilla i tested, works fine. use below code:

<a href="#" onclick="history.go(-1);return false;" style="text-decoration:underline;">Back</a>
like image 29
Viishnuu Avatar answered Oct 20 '22 18:10

Viishnuu