Misi
Misi

Reputation: 748

Displaying uninterpreted HTML code into a html iframe

I want to display a text with CR and tabs (let's say the code is into a var shtml) into a iframe without losing the ASCII characters.

<!--var shtml-->
<HEAD>
</HEAD>
<BODY style="FONT-SIZE: 12.5pt">
   mmm
</BODY>

My iframe

<iframe rows="5" cols="60" id="tahtml">
</iframe >

My JS

document.getElementById('tahtml').textContent = shtml; //innerText = shtml;

enter image description here

If I use .innerText then the code(shtml) is interpreted in Firefox. If I use .textContent the code(shtml) is displayed wihtout the ASCII characters. the jQuery .text() dose the same as .textContent.

Upvotes: 0

Views: 341

Answers (1)

Paul S.
Paul S.

Reputation: 66334

Just like an <input>, a <textarea>'s DOM interface (HTMLTextAreaElement) has a value property, it looks like you want to set this property to shtml.

document.getElementById('tahtml').value = shtml;

Demo


For an <iframe> make the MIME for the page loaded inside it text/plain. This can be done by, for example, fetching an empty .txt or setting the src to data:text/pain,. Then you can do the following

// don't collapse whitespace, only needed to be done once
ifrmDoc.documentElement.style.whiteSpace = 'pre';
// set text
ifrmDoc.documentElement.innerHTML = shtml;

Where

var ifrm = document.getElementById('tahtml'),
    ifrmDoc = ifrm.contentDocument || ifrm.contentWindow.document;

Of course, you could also do it by

  • writing the whole thing as a dataURI and pass it as the src
    ifrm.src = 'data:text/pain,' + window.encodeURIComponent(shtml);
  • appending your text using by using DOM methods and text nodes
    ifrmDoc.body.appendChild(ifrmDoc.createTextNode(shtml))
    (this would still require whiteSpace: pre;)
  • making a <textarea> or <pre> in your <iframe>, into which you put shtml as value or a text node, respectively.

Upvotes: 1

Related Questions