skip to Main Content

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.

3

Answers


  1. Change the file suffix to .html instead of .txt

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search