UNPKG

laceside

Version:

In-browser JavaScript IDE and execution environment

102 lines (86 loc) 3.12 kB
<html> <head> <link rel="stylesheet" href="styles.css"> <link rel="stylesheet" href="node_modules/codemirror/lib/codemirror.css"> <script src="node_modules/codemirror/lib/codemirror.js"></script> <script src="node_modules/codemirror/mode/xml/xml.js"></script> <script src="node_modules/codemirror/mode/javascript/javascript.js"></script> <script src="node_modules/codemirror/mode/css/css.js"></script> <script src="node_modules/codemirror/mode/htmlmixed/htmlmixed.js"></script> <script src="node_modules/codemirror/addon/edit/matchbrackets.js"></script> <script> var editor; function config(){ editor = CodeMirror.fromTextArea( document.getElementById( "codeWindow" ), { lineNumbers: true }); //editor.setSize( { width: '100%', height: '800px' } ); takeOverConsole(); } function run(){ // clean up previous execution document.querySelector( "#codeConsole" ).innerText = ""; var doc = document.getElementById('iframe').contentWindow.document; if( doc.querySelector( "#codeBlock" ) !== null ){ doc.head.removeChild( doc.querySelector( "#codeBlock" ) ); } var scriptTag = doc.createElement("script"); scriptTag.setAttribute( "id", "codeBlock" ); doc.open(); var inline = doc.createTextNode( editor.getValue() ); scriptTag.appendChild( inline ); doc.write( "<html><body></body></html>" ); doc.head.appendChild( scriptTag ); doc.close(); } // this bit of code based on solution: // http://tobyho.com/2012/07/27/taking-over-console-log/ function takeOverConsole(){ var win = document.getElementById('iframe').contentWindow; var console = window.console; if (!console) return; function intercept(method){ var original = console[method]; console[method] = function(){ // capture and push to our output div window.document.querySelector( "#codeConsole" ).innerText += Array.prototype.slice.apply(arguments).join(' ') + "\n"; if (original.apply){ // Do this for normal browsers original.apply(console, arguments); }else{ // Do this for IE var message = Array.prototype.slice.apply(arguments).join(' '); original(message); } } } var methods = ['log', 'warn', 'error']; for (var i = 0; i < methods.length; i++) intercept(methods[i]); } </script> </head> <body onload="config();"> <h3>livesandbox - in-browser JavaScript environment</h3> <div class="row"> <div class="col-50"> <form> <div class="row" id="codeDiv"> <label for="codeWindow">Write some code here ...</label> <textarea id="codeWindow"></textarea> </div> <div class="row" id="consoleDiv"> <label for="codeConsole">Console output ...</label> <div id="codeConsole"> </div> </div> <button type="button" onclick="run();">Run</button> </form> </div> <div class="col-50"> <label for="iframe">HTML document ...</label> <iframe id="iframe"></iframe> </div> </div> </body> </html>