Kazomix
Kazomix

Reputation: 9

How do I make an HTML page interpret a TXT file as HTML code?

All I've found is how to display the data of the TXT file, but I want to be able to use that TXT file to be interpreted and used as HTML code to be displayed instead.

Upvotes: 0

Views: 353

Answers (3)

Brooke
Brooke

Reputation: 372

I used a very slightly modified version of derder56's code for this example that takes HTML code from a text file and outputs it in the result div. Of course, you could do anything with the result from the text file, such as outputting it in the console.

<body>
<div id="result"></div>
</body>

<script>
    fetch('file.txt').then(e => e.text()).then(txt => {
        document.getElementById("result").innerHTML = txt;
    })
</script>

Keep in mind that due to a CORS security advisory, you wouldn't be able to do this with local files due to CORS requests requiring HTTP or HTTPS.

Upvotes: 0

derder56
derder56

Reputation: 361

If you mean JavaScript, your only option would be to do something like this:

fetch('/file.txt').then(e=>e.text()).then(txt=>{
  let txtFunc = new Function(txt)
  txtFunc()
})

Note that eval or new Function is not safe and should not be used in most cases.

Upvotes: 2

Johannes
Johannes

Reputation: 67778

Change the file suffix to .html instead of .txt

Upvotes: 0

Related Questions