Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript redirect (location.href) breaks the Back button unless setTimeout() is used

I just came across some odd behavior in Firefox 3.6/Mac. I suspect that it's general Firefox behavior, though.

I created two dead-simple test pages that change the window.location.href property to navigate to new URL:

  • http://troy.onespot.com/static/stack_overflow/redirect.html
  • http://troy.onespot.com/static/stack_overflow/redirect_timeout.html

If you try the following with either file:

  • Open a new/blank browser tab.
  • Paste the URL and hit "Enter".

You'll notice one difference between the two: using the first link, the browser's "Back" button is disabled; using the second, it's enabled and works as I'd expect it to.

The only difference between the two scripts is that the latter sets a one-second timeout before changing window.location.href.

I don't know why this happens, and I'm trying to achieve the behavior of the second script (where the "Back" button continues to work as expected) without causing any delay for the user.

My best guess is that maybe Firefox treats an immediate "redirect" by setting window.location.href the same as using the window.location.replace() method, since I think it's common for developers to use the former when they meant to use the latter. Maybe using setTimeout, since that causes the code to run asynchronously, defeats this behavior. Could that be the case?

I haven't experimented with the minimum value for setTimeout to achieve the desired effect, but I'll do that now. I would like to figure out why this happens exactly, though.

Thanks!

like image 838
Bungle Avatar asked Oct 26 '22 06:10

Bungle


1 Answers

You are right in assuming that setting location.href while a page is loading is treated as a replace. There are in fact two separate behaviours.

The first is that setting location.href from script running as the result of parsing a tag is always interpreted as a replace. This was implemented to mirror Netscape 4 behaviour and subsequently tweaked.

The second is that any new document loaded as the result of an onload handler is also always interpreted as a replace. This was implemented and also tweaked.

But I'm curious as to why you are so keen to do this, as means that users would have to use the Back drop-down menu to go to the page before your page. (Going back one page would be no use if it kept on redirecting them to the current page.)

like image 100
Neil Avatar answered Dec 09 '22 22:12

Neil