If the iframe is in the same domain, as it seems to be the case, let's imagine that your document says:
<iframe id="el_iframe" src="info/info_template"></iframe>
In that case you can capture the HTML content as:
var iframeDocument = document.getElementById('el_iframe').contentDocument;
var iframeHTML = iframeDocument.body.innerHTML;
or
var iframeText = iframeDocument.body.innerText;
If you do not work contentDocument
you can try using
var iframeDocument = document.getElementById('el_iframe').contentWindow.document;
EDIT:
If the iframe or its source are defined in a style variable:
var info = "<iframe src='info/info_template'></iframe>";
You can follow the flow described above by inserting the iframe on your page. I left you a plunkr with the example:
link
EDIT2
The above can be done perfectly with ajax (I left you another example plunkr )
var info = '<iframe src="iframe.html"></iframe>';
var iframe_url=jQuery(info).attr('src');
jQuery.ajax({
method: 'get',
url: iframe_url,
dataType: 'html'
}).then(function (iframeHTML) {
document.getElementById('editor').innerText = iframeHTML;
document.getElementById('iframe_html').innerHTML = escapaHTML(iframeHTML);
});
By using this approach the content comes to you complete: <html>...</html>
instead of just the content of body
.
Keep in mind that an ajax call is asynchronous. In the example, everything you want to do with the response of the request must occur within the loop defined by .then(function(iframeHTML) { .... });
. Outside the loop there is no variable iframeHTML
and even if you assign it to a global variable, it will not be defined correctly before the promise is resolved.
(an exception to this would be to use async / await + babel, but seriously, seriously, we will not go into that topic in this answer)
Eye
If you want to use the HTML content of the iframe, and treat it as text (for example, put it in a <pre>
element to show the source code) you have to escape the content, for example by replacing <
with <
and >
by >
. There are other characters that you should not put in a textarea without escaping, but I think it is beyond the scope of this question. This I tell you because if you insert the HTML of the iframe, its content is applied to the main page. The scripts are not executed, but the styles, for example, do apply if you do not escape them:
The iframe has a style that defines font-weight:bold;
throughout the document. If it says:
document.getElementById('iframe_html').innerHTML = escapaHTML(iframeHTML);
You would instead:
document.getElementById('iframe_html').innerHTML = iframeHTML;
This would cause the import of the content of the iframe to affect the style of the main document.