Search code examples
htmliframehyperlinkhref

iframe with srcdoc: same-page links load the parent page in the frame


Same-page links work by referencing another element that has id="sec-id" on the same page, using

<a href="#sec-id"></a>

for instance. A link like this is relative.

However, if I use that very same syntax in the iframe in my LaTeX.js playground, it will not just scroll to the destination element, but (re)load the whole playground page inside the ifame. (Note that I set the contents of the iframe programmatically with iframe.srcdoc = html)

Example: LaTeX.js playground, right at the end of the first section click on the link in "See also Sec­tion 11." in the iframe on the right side.

What could be the reason?

UPDATE: I now understand the source of the problem: the browser uses the document's base URL to make all relative URLs absolute (see <base>). The trouble starts with an iframe that has its content set with srcdoc: no unique base URL is specified, and in that case the base URL of the parent frame/document is used--the playground in my case (see the HTML Standard).

Therefore, the question becomes: is there a way to reference the srcdoc iframe in a base URL? or is it possible to make the browser not prepend the base? or to make a base URL that doesn't change the relative #sec-id URLs?


Solution

  • What about catching the event and scrolling to the desired anchor?

    $("a").click(function(e) {
        $('.iframe').animate({
           scrollTop: $(e.target.attr('href')).offset().top
        }, 2000);
        return false;
    });