Skip to content Skip to sidebar Skip to footer

Try It Yourself Editor Js

I have created a very simple editor that has been working great. However, I just tried to put JavaScript into it and I can't get it to work. The code for the editor:
window.myScope = {
    update: function() {
        var div = document.createElement('div'),
            codeinput = document.getElementById('codebox').value,
            scriptcode = "";

        div.innerHTML = codeinput;
        Array.prototype.slice.apply(div.querySelectorAll("script")).forEach(function(script) {
            scriptcode += ";" + script.innerHTML;
            div.removeChild(script);
        });
        window.frames[0].document.body.appendChild(div);
        // hackers love to see user input eval'd like this...eval(scriptcode);
    }
};

And then you would update your button like so:

<inputid="button" onclick="myScope.update();"type="button" value="Update page">

Or, even better, use addEventListener and forget the onclick part altogether. I'll let you do that research on your own ;)

Solution 2:

JavaScript inserted via innerHTML will not be executed due to security reasons:

HTML5 specifies that a <script> tag inserted via innerHTML should not execute.

from MDN: Element.innerHTML - Security considerations, see also: W3: The applied innerHTML algorithm.

A possible solution using the jQuery method .append() works around that, as it somehow evals the content. But this will still not solve your problem, as the JavaScript code is executed in the current scope. Here's a test scenario:

functionupdate() {
    var codeinput = document.getElementById('codebox').value;
    $(window.frames[0].document.body).append(codeinput);
}

Try it here

Try to insert this script:

<script>alert( document.getElementById('tryitcontainer') );
</script>

and this one:

<pid="test">Test</p><script>window.frames[0].document.getElementById('test').innerHTML = 'updated';
</script>

The first one will return a [object HTMLDivElement] or similar. Here you can see, that you're still in the same scope as the parent frame. The second one will correctly update the content within the iframe. Keep that in mind, when experimenting with those things.

Maybe Executing elements inserted with .innerHTML has some more infos for you.

Post a Comment for "Try It Yourself Editor Js"