1

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 B in the new window,
  • go back on A page using back link (history.length, then location.href=document.referrer)
  • history.length incremented to 2
  • press browser back button or backspace to go back to B page
  • click on back link and there is an error (it should go back to the A, but stays on B because history.length is 2 and history.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

Community
  • 1
  • 1
Boris Šuška
  • 1,796
  • 20
  • 32
  • don't do this, but simply push history state when your page content changes in a way that you believe is a "new state". See https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history -- that way the back/forward buttons always do the right thing. – Mike 'Pomax' Kamermans Apr 01 '14 at 17:36
  • It looks great, but it have to work in IE8 too – Boris Šuška Apr 01 '14 at 17:39
  • no it doesn't. In 7 days, windows XP support ends, even for corporate accounts. With it, IE8 support dies. You literally have a week longer to care about it, might as well stop now. – Mike 'Pomax' Kamermans Apr 02 '14 at 01:12
  • Ok, but what about IE 9, pushState is supported from version IE 10 – Boris Šuška Apr 02 '14 at 09:07
  • IE9 is a bypass version. If you were still on windows XP, IE8 was your only option (MS would not give you 9, 10 or 11). If you're on Windows 7 or Windows 8, MS has been pushing you onto IE 11 already (and so the only reason you'd still be in IE9 is personal choice. Even corporate clients will not be on IE9 anymore). If you look at global stats, you'll see IE8 and IE11 as the two significant IE versions. – Mike 'Pomax' Kamermans Apr 02 '14 at 21:37

0 Answers0