htmlpreviewblockly

How do I preview HTML in real time on my HTML page


I'm trying to build a tool that allows you to create a HTML-page using Blockly-Blocks (Blockly). It is a HTML-page that looks like this at the moment:

Image

It can already create code out of blocks, but now I need a way to preview the result live on the page in the upper right corner. Does anyone have an idea how that could be somewhat easily implemented? I've looked around a bit but only found tools that are able to Live-Preview HTML but none to use in your own page.


Solution

  • You could document.write the page into an iFrame

    This will alas not work here at SO since iFrames are sandboxed

    but it does work in a jsfiddle

    enter image description here

    const ifr = document.preview;
    const html = `<!doctype html>
      <html>
        <head>
          <meta charset="utf-8" />
          <title>Preview</title>
        </head>
        <body>
          <div style="font-family:Ariel, sans-serif; background-color: #ffcc00; color: #003300">
            <ol>
              <li>Line 1</li>
              <li>Line 2</li>
            </ol>
          </div>  
        </body>
      </html>`;
    ifr.document.write(html);
    ifr.document.close();
    #preview {
      width: 500px;
      height: 500px;
      float: right;
    }
    <iframe name="preview" id="preview"></iframe>

    PS: Your HTML is malformed. It has tags belonging to the body in the head and is missing body tags - see my example above for a correct html page

    enter image description here