Creating Page With Similar Objective To JSfiddle Site

1

Since I had to open the favorite text editor to create HTML page to perform CSS and JScript tests, I decided to create a personal page based on some aspects of third-party sites like "Jsfiddle", a very simple code, I'm not proud of him. I just did it because it speeds up my development without first having to create the final file (HTML document).

Code

<html>

<head>

<style>

#menu-vertical
{
    position: fixed;
    z-index: 999; 
    overflow: hidden;
    border-right: 1px dashed silver;
    padding: 5px;
    height:100%;
    float: left;
}

textarea
{
    width: 100%;
    height: 150px;
    border: 3px solid silver;
    padding: 5px;
    font-family: Tahoma, sans-serif;
    background-color: azure;
    background-position: bottom right;
    background-repeat: no-repeat;
}

input 
{ 
width: 90px;
    border: 1px solid gray;
    padding: 5px; 
}

</style>

<script>
<!--

function pop()
{
var js = document.getElementById("JS").value;

var html = document.getElementById("HTML").value;

var css = document.getElementById("CSS").value;

var janela = window.open("", "janela","width=500px, height=500px, scrollbars=yes");

janela.document.write("<html>\n<head>\n");

janela.document.write("<style>\n"+css+"\n</style>\n");

janela.document.write("</head>\n<body>\n"+html+"\n");

janela.document.write("</body>\n<script>\n"+js+"\n");

janela.document.write("</script>\n</html>");
}

//-->
</script>

</head>

<body>

<!-- Editor Lang.: CSS - HTML - JS -->
<div id="menu-vertical">

<br><b>CSS:</b><br>

<textarea id="CSS" cols="39" rows="9" size="1"></textarea>

<br><b>HTML:</b><br>

<textarea id="HTML" cols="39" rows="9" size="1"></textarea>

<br><b>JScript:</b><br>

<textarea id="JS" cols="39" rows="9" size="1"></textarea>

<center>

<hr color="silver" width="100%" size="1"/>

<input type="button" value="Executar" onclick="pop()"/>

</div>
<!-- Fim -->

</center>

</body>

</html>

var js = document.getElementById("JS").value;

var html = document.getElementById("HTML").value;

var css = document.getElementById("CSS").value;

Dynamic iframe

pag = function ()
{
var el = document.createElement('iframe');
el.setAttribute('id','exibir') ;
el.width ="100%";
el.height="100%";
document.body.appendChild(el);
}

I quote something related to this question ..

Diddle - "This is a simplified clone of jsFiddle created by nwoike"

Source: How to create a simplified version of jsFiddle

    
asked by anonymous 26.07.2016 / 18:11

1 answer

6

I recommend first to create a iframe using the sandbox attribute, this to "try" to bring some security, preferably what can do in HTML do, to be creating dynamic things with JS works well, but it takes time and makes the most complex maintenance, so what can be HTML do in HTML.

The values of the sandbox attribute:

  • allow-same-origin: Allows content to be treated as being from its normal source. If this key is not used, the embedded content is treated as being from a single source.

  • allow-top-navigation: Allows the embedded navigation context to navigate content (load) to the top-level navigation context. If this key is not used, this operation is not allowed.

  • allow-forms: Enables embedded navigation context to submit forms. If this key is not used, this operation is not allowed.

  • allow-popups: Allows popups (such as from window.open).

  • allow-scripts: Allows embedded navigation context to execute scripts (but does not create pop-up windows). If this key is not used, this operation is not allowed.

  • allow-pointer-lock: Allows the embedded navigation context to use the Pointer Lock API.

You can use the IFRAME attribute that should change is srcdoc , but to debug the code you can use URL.createObjectURL , so it is possible to detect the line that gave problem (@TobyMosque tip).

Make html structure look like this:

<!DOCTYPE html>
<html>
<head>
    <title>Sandbox</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <style type="text/css">
    .fiddle textarea, .fiddle iframe {
        width: 420px;
        height: 240px;
    }
    </style>
</head>
<body>
    <form class="fiddle">
        html:<br>
        <textarea id="fiddle-html">
        &lt;div class="foo"&gt;Foo bar&lt;/div&gt;
        &lt;p&gt;Baz&lt;/p&gt;
        </textarea>
        <hr>

        css:<br>
        <textarea id="fiddle-css">
        .foo {
            background-color: #f00;
            color: #fff;
        }

        p {
            color:red
        }
        </textarea>

        <hr>

        javascript:<br>
        <textarea id="fiddle-js">
        setTimeout(function() {
            alert("Olá mundo");
            console.log(1, 2, 3);
        }, 2000);
        </textarea>
        <hr>

        <iframe id="fiddle-sandbox" sandbox="allow-same-origin allow-scripts allow-popups allow-forms allow-modals"></iframe>

        <hr>

        <button type="button" id="run">Testar</button>
    </form>

    <!--// O script precisa ficar no final pois assim é mais rápido que onload -->
    <script type="text/javascript" src="fiddle.js"></script>
</body>
</html>

The fiddle.js should get the contents of the fields like this (requires HTML5 support):

(function () {
    var
        currentUrl,
        currentContent,
        iframeContent;

    var
        running = false,
        supportBlob;

    var
        runButton = document.getElementById("run"),
        jsField   = document.getElementById("fiddle-js"),
        cssField  = document.getElementById("fiddle-css"),
        htmlField = document.getElementById("fiddle-html"),
        result    = document.getElementById("fiddle-result"),
        target    = document.getElementById("fiddle-sandbox");

    var mainCharset = "characterSet" in document ?
                        document.characterSet : (
                            document.inputEncoding ||
                            document.charset ||
                            document.defaultCharset
                        ) || "UTF-8";

    var tpl = '<!DOCTYPE html>\n' +
                '<html>\n' +
                '<head>\n' +
                '<meta http-equiv="X-UA-Compatible" content="IE=Edge">\n' +
                '<meta http-equiv="Content-Type" content="' +
                'text/html; charset=' + mainCharset + '">\n' +
                '<title>Running<\/title>\n' +
                '<style type="text/css">\n{%css%}\n<\/style>\n' +
                '<\/head>\n' +
                '<body>\n' +
                '{%html%}\n' +
                '<script type="text\/javascript">\n{%js%}\n<\/script>\n' +
                '<\/body>\n' +
                '<\/html>';

    //Adiciona evento ao botão testar
    runButton.onclick = runEvt;

    checkIframe();

    function checkIframe(callback)
    {
        setTimeout(function() {
            iframeContent = target.contentWindow ||
                            target.contentDocument.document ||
                            target.contentDocument;

            if (callback) {
                callback();
            }
        }, 10);
    }

    function writeInFrame()
    {
        result.removeChild(target);
        target.src = "about:blank";
        result.appendChild(target);

        checkIframe(function() {
            iframeContent.document.open();
            iframeContent.document.write(currentContent);
            iframeContent.document.close();

            running = false;
        });
    }

    function runEvt()
    {
        if (running) {
            return;
        }

        running = true;

        currentContent = tpl.replace(/\{%css%\}/,  cssField.value)
                            .replace(/\{%js%\}/,   jsField.value)
                            .replace(/\{%html%\}/, htmlField.value);

        if (supportBlob === false || !URL.createObjectURL) {
           writeInFrame();
           return;
        }

        //Remove URL antiga, se existir
        if (currentUrl) {
            URL.revokeObjectURL(currentUrl);
        }

        var blobData = new Blob([currentContent], { "type": "text/html" });

        //Cria url com os dados do Blob
        currentUrl = URL.createObjectURL(blobData);

        //Troca src do iframe
        target.src = currentUrl;

        //IE11 não carrega urls do tipo 'blob:', isso é um pequeno teste
        if (typeof supportBlob !== "boolean") {
            setTimeout(function() {
                try {
                    supportBlob = iframeContent.location.href === currentUrl;
                } catch (ee) {
                    //Se o navegador não suportar o sandbox ocorre erro de segurança
                    supportBlob = false;
                }

                if (!supportBlob) {
                    writeInFrame();
                }

                running = false;
            }, 50);
        }
    }
})();
    
27.07.2016 / 00:49