PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, December 2, 2022

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

 December 02, 2022     html, iframe, javascript, jquery     No comments   

Issue

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.


Solution

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.



Answered By - Alexander O'Mara
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing