Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 487
hmc Avatar asked Sep 05 '14 03:09

hmc


People also ask

How do I view the source of an iframe?

To see the source of an individual frame, right-click or Ctrl -click the frame and select This Frame, and then View Frame Source. Internet Explorer: From the View menu (IE 9) or the Page menu (IE 8), select Source. If the menu bar is hidden, press Alt to make it visible.

How can I get iframe HTML code using jQuery?

Answer: Use the jQuery contents() method You can use the jQuery contents() method in combination with the find() , val() and html() methods to insert text or HTML inside an iframe body.

How can I access iframe element with JavaScript?

Getting the element in IframegetElementById() method by passing iframe id as an argument. const iframe = document. getElementById("myIframe"); Now, it has and contentWindow property which returns the document object by using that we can access the elements from an Iframe.

Can you access the content of an iframe?

You could use . contents() method of jQuery. The . contents() method can also be used to get the content document of an iframe, if the iframe is on the same domain as the main page.


1 Answers

Use documentElement instead of body and outerHTML instead of innerHTML.

Example:

document.getElementById("iframe_id").contentWindow.document.documentElement.outerHTML

Note that this will exclude the doctype and any comments that are not a child of the HTML node. If you need to include this data, you will need to make a separate AJAX request to fetch it. The doctype could also be reconstructed from document.doctype.

like image 83
Alexander O'Mara Avatar answered Sep 22 '22 16:09

Alexander O'Mara