invisiblegg 发布的文章

一个页面版的浏览器控制器输出


今天同学突然问我廖老的站立有个在输入框里输入js代码 就能像console里边一样的输出这里来段代码

<textarea id="code">console.log('123')</textarea>
<button onclick="exe()">t</button>
<div id="text"></div>
<script>

function exe(){
    var t=document.getElementById('code').value
    execute_javascript(t)
}
function execute_javascript(code) {
    
    var code = code;

    // var code = "";
    (function () {
        // prepare console.log
        var
            buffer = '',
            _log = function (s) {
                // console.log(s);
                buffer = buffer + s + '\n';
            },
            _warn = function (s) {
                // console.warn(s);
                buffer = buffer + s + '\n';
            },
            _error = function (s) {
                // console.error(s);
                buffer = buffer + s + '\n';
            },
            _console = {
                trace: _log,
                debug: _log,
                log: _log,
                info: _log,
                warn: _warn,
                error: _error
            };
        try {
            eval('(function() {\n var console = _console; \n' + code + '\n})();');
            if (!buffer) {
                buffer = '(no output)';
            }
            document.getElementById("text").innerHTML=buffer
        }
        catch (e) {
            buffer = buffer + String(e);
        }
    })();
}
</script>