Skip to content Skip to sidebar Skip to footer

Can An Iframe Display Source Code Only?

Is possible for an iFrame to show the raw code of a source rather than rendering it out? If so how do you do that and can it be done on JavaScript?

Solution 1:

Not directly, but there's no reason it cannot be done with Javascript. Make an AJAX call to fetch the HTML source, HTML-encode a few key characters, and set the result as the contents of your frame or other element.

Solution 2:

You can set the src attribute to a page on your webserver that outputs the html as plain text and not as HTML. Therefor you must set the header info content-type to text/plain. Check this page to see how it's done in PHP: http://www.jonasjohn.de/snippets/php/headers.htm

There is no way to do this with html or js only. You'll need some server side language to render the page. Of course it is possible to retrieve the data from the webserver in js through an xmlhttprequest, better known as AJAX.

Solution 3:

You have two main ways to do so:

  1. If you want to do it on the backend side, you have to modify the Content-Type header of the response to text/plain. That way, the browser will not render HTML code when loading the page. The implementation will depend on your stack.

  2. If you want to do it on the client side, with Javascript, you can extract the code from the iframe element, like so:

<iframeid="myIframe"src="https://example.org"></iframe><script>const iframeElement = document.getElementById('myIframe');
let rawHtml = null;

// We extract the code each time the iframe element is loaded// If we try to do it before that moment, we won't get any HTML
iframeElement.addEventListener('load', function () {
  console.log('HTML loaded and available in rawHTML variable');
  rawHtml = iframeElement.contentDocument.documentElement.innerHTML;
});
</script>

This snippet does not work on JSFiddle! I bet this is due to security measures taken when loading the iframe.

More about iframes and iframe security considerations: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe

Solution 4:

No. You need a tool to convert the HTML into text to display.

Post a Comment for "Can An Iframe Display Source Code Only?"