Embed JS Console within website

前端 未结 3 1235
孤城傲影
孤城傲影 2020-12-18 00:46

I want to embed a JS-Console within a website for extended debugging purposes. Are there any libraries or hooks available? How can I catch console.log messages?

相关标签:
3条回答
  • 2020-12-18 01:18

    You can override console.log

    <div id="console"></div>
    

    script :

    if (window.console) console = { 
        log: function(){
            var output='',
                console=document.getElementById('console');
            for (var i=0;i<arguments.length;i++) {
                output+=arguments[i]+' ';
            }
            console.innerText+=output+"\n";
        }
    };
    
    //test
    var test=12345;
    console.log('test', 'xyz', test);
    
    0 讨论(0)
  • 2020-12-18 01:27

    You could use the eval() function to evaluate javascript in a string and then print that output to some div. This would give you some capabilities of a REPL.

    const consoleElm = document.querySelector('#console');
    const clearButton = document.querySelector('#clear');
    
    clearButton.addEventListener('click', (event) => {
    	consoleElm.innerHTML = '';
    });
    
    const consoleForm = document.querySelector('#console-form');
    consoleForm.addEventListener('submit', (event) => {
    	event.preventDefault();
      const command = event.target.querySelector('#command').value;
      const value = eval(command);
      consoleElm.innerHTML += (value === undefined ? 'undefined' : value) + '\n';
    });
    <div>
      <form id="console-form">
        <input type="text" id="command">
        <input type="submit" value="Run Command">
        <button id="clear" type="button">Clear</button>
      </form>
      <hr>
      <pre id="console"></pre>
    </div>

    0 讨论(0)
  • 2020-12-18 01:41

    How can I catch console.log messages?

    You can monkey-patch the real console.log method and do whatever you like with the input:

    var realConsoleLog = console.log;
    console.log = function () {
        var message = [].join.call(arguments, " ");
        // Display the message somewhere... (jQuery example)
        $(".output").text(message);
        realConsoleLog.apply(console, arguments);
    };
    

    Here's a working example. It logs calls to console.log in the .output element, as well as in the console like usual.

    0 讨论(0)
提交回复
热议问题