Home > Back-end >  How to feed code into iframe without a URL or FILE?
How to feed code into iframe without a URL or FILE?

Time:07-05

I'm trying to create a visual editor where the user creates a 3D scene, and my application writes the code for the project itself. I want to create a testing feature where the code that was generated is run. I've looked into using iframes, but as far as I know, you need a specific URL for iframe.

Here are some ideas/solutions I've come up with:

  • Is there a way to manually feed code to an iframe, without a file or URL?
  • Is there any other easier way to accomplish this task?
  • Can this be done without server side code?

Let me know if you need any more information. Thanks!

CodePudding user response:

Yes it is possible however a much simpler way would be to just create another html file somewhere on your server/host and just disallow external access to it so it's only accessible from the iframe.

You have to use an script to give code to an iframe without a source file like this:

<iframe id="my-iframe"></iframe>

<script>
document.getElementById("my-iframe").contentDocument.write("<h1>Hello World</h1>");
</script>

Change the JavaScript to this to overwrite all of the content of the iframe:

var iframe = document.getElementById("my-iframe");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;

iframeDocument.body.innerHTML = "<h1>Goodbye World</h1>";

This overwrites all the content of the iframe with your own.

This will work but it will be a big pain to format the html from the iframe. Also as far as I know this is the simplest way that fits your needs.

  • Related