Making linking between anchors in an IFrame work in Firefox 4 and above

Update: For Firefox versions 11 and up see the update code.

In Firefox 4 a security fix was added which prevents linking between anchors within an IFrame that does not have scroll bars. This change breaks the scenario where you have an IFrame that has a “Go To Top” link (<a href=”top”>Go to top</a>) which links to an anchor tag (<a name=”#top” />) at the top of the IFrame.  If this IFrame does not have scroll bars then clicking the link will scroll the parent page to bring the anchor into view. This can be a security issue which is why Firefox is the first browser to block it.  However, I believe they should have added an exception for the case when the IFrame and the containing page satisfy the Same Origin Policy.

I worked around this limitation by adding the following code to my IFrame (my implementation uses jQuery) which will override the anchor link functionality and scroll the window programmatically. This code makes use of the window.parent property which means it is subject to the Same Origin Policy.

$(function(){
  $("a").each(function (){
    var link = $(this);
    var href = link.attr("href");
    if(href && href[0] == "#")
    {
      var name = href.substring(1);
      $(this).click(function() {
        var nameElement = $("[name='"+name+"']");
        var idElement = $("#"+name);
        var element = null;
        if(nameElement.length > 0) {
          element = nameElement;
        } else if(idElement.length > 0) {
          element = idElement;
        }

        if(element) {
          var offset = element.offset();
          window.parent.scrollTo(offset.left, offset.top);
        }

        return false;
      });
    }
  });
});