Creating a Page Similar to Jsfiddle Site

Asked

Viewed 367 times

1

Since I have to Open the favorite text editor to create HTML page in order to perform CSS and Jscript tests, I decided to create a personal page based on some aspects of third-party sites like "Jsfiddle", very simple code, no, I’m not proud of it. I only 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>

Otherwise perfect, now I want to replace the Pop-up Window to iframe dynamic, I’m just not able to recreate the function variables pop() for the function pag() of iframe.

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 - "It is a simplified jsFiddle clone created by nwoike"

Source: How to create a simplified jsFiddle version

  • Start with the idea of creating a iframe on the page and not a new window.

  • Diego just to warn had some errors in the response code, now corrected, I hope it helps.

  • Which browser you want to run, not everything will be possible :/ ... I will try to edit

  • @Guilherme Nascimento Your answer already pleases me! I won’t have to change it because of this. But knowing otherwise to cover modest browsers, just add another logic below the first answer, if you know, nothing mandatory Okay! As for the Navigator I use a certain variety familiar at least known is why I wish to be portable Firefox2,3.. Ieca rsrs Konqueror

  • Okay Diego, I was able to test on IE6, too many browsers I don’t know what the effect will be, but I believe it works.

  • @Guilherme Nascimento Tested on: Konqueror Light, Flock 1.0, Flock 1.5, Firefox 1.0.4, Firefox 1.5.0.6, Firefox 2.0, Opera 8.01, Opera 8.01, Opera 8.25, Opera 8.50, Opera 8.52, Opera 9.10, Opera 9.25, .. finally I think it is better to resort some plugins for this specific case, use the features of the new versions and provide shims or polyfills, that simulate those features. In the other good work, I’m grateful you spent your valuable time helping me. From now on let me.

Show 1 more comment

1 answer

6


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

The values of the sandbox attribute:

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

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

  • allow-Forms: Allows embedded browsing context to send forms. If this key is not used, this operation is not allowed.

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

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

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

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

Make html structure would 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 must download 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);
        }
    }
})();
  • 4

    I think in the case of the AP it might be interesting to use URL.createObjectURL to create separate documents for the CSS, JS and HTML, and set the src towards the iframe to the link HTML, this way it is easier even for him to add a function to open the snippet in another window and debug Javascript.

  • @Tobymosque great idea :)

  • @Tobymosque Legal, your intention here is all geared to "iframe" very similar to this As I put a button inside iframe I cite it as source reference in parts, where you responded to the creation of the HTML document in memory.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.