Wednesday, 11 November 2020

How to read the *original* source of an iframe, after it has loaded, from the cache

The most generic way to describe this is that I want to fire only one network request, only after the client has seen a certain part of the viewport, and then use it and display it in an iframe, in the most efficient manner possible.

Given a DOM structured like so:

<!DOCTYPE html>
<html>
  <head />
  <body>
    ...
    <iframe loading="lazy" sandbox="" src="http://www.example.com" />
    <pre />
    ...
  </body>
</html>

I want to show the client, in the pre tag, what the source of the iframe above looks like. The iframe element may host an arbitrary document, it may be textual or binary, all that is known is that the browser can display it. The iframe's source URL is hosted on the same origin.

I am aiming to display what one would see by going to a Chromium "view-source:" URL, or similar.

Accessing the .contentWindow or .contentdocument properties may not be possible, as it is sandboxed entirely, but even if I could, the document's outerHTML would not be sufficient, and using an XMLSerializer would obviously change the output. Also, I believe that browsers are allowed to edit certain areas of a document, such as unnecessary whitespace, or formatting.

I had simply tried the following:

document
.body
.querySelector("iframe")
.addEventListener(
    "load",
    async ( { currentTarget: { src } } ) => {
        const data = await fetch(
            src, {
                cache: "only-if-cached"
            }
        );

        // ... use data
    }, {
        passive: true,
        once: true
    }
);

Yet, the fetch failed. It seemed that the URL was not in the browser's cache, but I did not want to initiate a new network request, is there an efficient way that I could do this?

I was thinking of using an Intersection Observer as a potential solution because it would result in only one network request, but the code was pretty long, and it seemed to not have been working correctly (I am inexperienced with the observer).



from How to read the *original* source of an iframe, after it has loaded, from the cache

No comments:

Post a Comment