2

I need to create a back link. I was adviced to use this to do it:

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

But it works only in IE and Mozilla, but not in Safari, Google Chrome and Opera. How to fix it?

pragmus
  • 3,513
  • 3
  • 24
  • 46
  • 3
    Works on my Chrome, which is the latest (43.0.2357.124) – musefan Jun 15 '15 at 14:50
  • 1
    possible duplicate of [webkit / Chrome history.back(-1) onclick vs href](http://stackoverflow.com/questions/14815838/webkit-chrome-history-back-1-onclick-vs-href) – Pogrindis Jun 15 '15 at 14:51
  • 1
    works in IE but doesn't in Chrome, Safari and Opera? well, I've never heard such in my life. – briosheje Jun 15 '15 at 14:52

2 Answers2

4

You're blocking the redirection using the href,

replace

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

with

<a onclick="window.history.back();">Back</a><--!javascript: is not required-->

or

Add a return false; to it.

<a href="#" onclick="window.history.back();return false;">Back</a>
Uma Kanth
  • 5,659
  • 2
  • 20
  • 41
3

The problem of your code is the onclick's value. The "protocol" javascript: is only required if you use JavaScript code within the href attribute. This signals your browser that the protocol of the link is not http: or https: but javascript:.

If you use the onclick attribute, the browser already knows that the value will be JavaScript, because all attributes like onclick, onfocus, onchange, ... require JavaScript as it's value.

This will work:

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

Adding return false; as a second command will prevent the site from jumping to the top, but that's not required.

Alex
  • 744
  • 8
  • 20