hmc
hmc

Reputation: 83

How to get full source code from an iframe with javascript or jquery?

I am helpless. I need to get the source code from an iframe with Javascript or Jquery.

The source file of the iframe is in the same domain. Here is my iframe:

<iframe src="/source_file.html" id="iframe_id"></iframe>

I am using the following so famous syntax to get the source code from the iframe:

document.getElementById("iframe_id").contentWindow.document.body.innerHTML

But with this code, I am only able to get the code inside BODY element. I want to get full code from <!doctype html> to <html>.

Please help me.

Upvotes: 5

Views: 13346

Answers (1)

Alexander O&#39;Mara
Alexander O&#39;Mara

Reputation: 60527

Keep in mind that in order to do this you will have to satisfy same-origin policy.

You can get most of the current DOM as HTML using documentElement instead of body and outerHTML instead of innerHTML.

console.log(document.getElementById('iframe_id').contentDocument.documentElement.outerHTML);

Note that this will exclude the doctype and any comments that are not a child of the HTML node.

If you also want to include that information, you can loop over the child elements.

function getIframeHtml(iframe) {
    const s = new XMLSerializer();
    let html = '';
    let e = iframe.contentDocument.firstChild;
    do {
        html += 'outerHTML' in e ? e.outerHTML : s.serializeToString(e);
        e = e.nextSibling;
    } while (e);
    return html;
}

console.log(getIframeHtml(document.getElementById('iframe_id')));

Note that this HTML code may not perfectly match the original HTML code (browser normalization or JavaScript may change it). For that you would have to use AJAX to read the HTML as text.

Upvotes: 9

Related Questions