Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 995
MiB Avatar asked Jun 02 '18 13:06

MiB


1 Answers

I don't know exactly how you could resolve this, I think it is because the srcdoc, you can't use the src with the content-type because the character limit, but you can convert it to a Blob and it kinda works, the style are lost though. Maybe you can use it as a starting point, based on your page:

// Get the document content
const doc = document.querySelector('iframe').srcdoc;
// Convert it to blob
const blob = new Blob([doc], {type : 'text/html'});
// Load the blob on the src attr
document.querySelector('iframe').src = URL.createObjectURL(blob);
// Remove srcdoc to allow src
document.querySelector('iframe').removeAttribute('srcdoc');
like image 195
Ander Avatar answered Oct 20 '22 18:10

Ander