Samul
Samul

Reputation: 2059

Make browser interpret txt as html

if I add an iframe inside a page and make the src="temp.txt" how can I make the browser interpret it as HTML instead of only displaying the content of "temp.txt"?

Upvotes: 0

Views: 525

Answers (2)

public override
public override

Reputation: 982

Or, if you don't want/have-access-to/permission to manipulate Apache files and your .txt file is at the same domain where your page is you can access <iframe>'s .textContent and replace <body>'s .innerHTML with it:

say you have an <iframe> in <body>:

<iframe id="frame01" src="afile.txt" width="550" height="400"></iframe>,

and say you have afile.txt file in same directory:

<p>HTTP/1.1 200 OK</p>
<p>Date: Sat, 13 Apr 2013 16:46:15 GMT</p>
<p>Server: Apache</p>
<p>Last-Modified: Fri, 08 Mar 2013 12:57:30 GMT</p>
<p>Accept-Ranges: bytes</p>
<p>Content-Length: 216469</p>
<p>Connection: close</p>
<p>Content-Type: image/jpeg</p>

you can replace page content by running this:

//
window.onload =
function () {
  var frame = document.getElementById("frame01");
  document.body.innerHTML =
    frame.contentWindow.document.body.textContent;
};
//
//

and output page shold look like:


HTTP/1.1 200 OK

Date: Sat, 13 Apr 2013 16:46:15 GMT

Server: Apache

Last-Modified: Fri, 08 Mar 2013 12:57:30 GMT

Accept-Ranges: bytes

Content-Length: 216469

Connection: close

Content-Type: image/jpeg


with htm tags parsed.

Upvotes: 0

Resorath
Resorath

Reputation: 1702

Browsers learn the MIME type of the file from what the web server tells the browser it is. Generally, web servers are configured so that .txt files are plain text files, and that the browser shouldn't try to interpret any markup in the file.

What you want is for the browser to get the mime type of "text/html". Three ways to do this;

1) Set the filename to temp.htm, this is the easiest

2) Change the web server so that txt files are now html files. In apache for example, you can add a line to httpd.conf that looks something like

AddType text/html .txt

and remove the line that looks like

AddType text/plain .txt

I wouldn't recommend this path, as this is a global change. You can try adding this to your .htaccess file in the directory your code resides in as well.

3) Use a dynamic language like PHP to set the file's mime type in transit. For example in PHP:

header('Content-type: text/html');

and then read the file to the browser.

Upvotes: 2

Related Questions