How to go back in browse history or to the location (referrer) only in case when history stack is empty (or non supported).
I'm trying to implement this back link in JavaScript like this:
<a href="javascript:history.length > 1 ? history.go(-1) : location.href=document.referrer;">Back</a>
Lets say I have three pages A, B, C.
This scenario is not working:
- starts on
A, - then open
Bin the new window, - go back on
Apage using back link (history.length, thenlocation.href=document.referrer) history.lengthincremented to 2- press browser back button or backspace to go back to
Bpage - click on back link and there is an error (it should go back to the
A, but stays onBbecausehistory.lengthis 2 andhistory.go(-1)is not working
I changed implementation to this by this (by this suggestion):
<a href="javascript:history.go(-1);location.href=document.referrer;">Back</a>
but this scenario is not working then: A -> B -> C <- B <- C (error, it should go to the A page)
Note: -> means forward, <- means click on the back link