Friday, May 08, 2009

Javascript history.back() not working for iframes in Firefox

Keywords:
javascript history frame iframe go(-1) back firefox 3 top self

Problem:
You can get a hyperlink to behave as a "back" with a bit of javascript:

<a href="javascript:history.back()">back</a>

or (saying go back one place in the history - equivalent to the above):

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


This works fine in all browsers when the page is in the main-view. If this javascript is encountered in an iframe you expect that you get the previous page that was loaded in that iframe. In firefox 3+ you're taken back in the main view page not the iframe - a nuisance if there's a detailed browsing history in the iframe view. Why does it work fine in other browsers and previous versions of firefox?

Solution:
I don't know why, but it seems that in firefox 3+ when you say history this becomes implicitly top.history. Someone has tried to raise this with mozilla with not much luck - javascript:history.back() and Firefox 3.0.1 and iframes.

The solution is to be explicit about which frame you want to navigate back with. If you just want all browsers to behave the same then self refers to the frame the user is clicking in (therefore in other browsers history is implicitly self.history). So the go-back hyperlink becomes:

<a href="javascript:self.history.back()">back</a>

or:

<a href="javascript:self.history.go(-1)">back</a>


This will behave the same regardless of if the page is loaded in the main-view or in an frame/iframe.