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.
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With