8

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?

NaN
  • 3,501
  • 8
  • 44
  • 77

3 Answers3

7

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.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
2

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);
davidkonrad
  • 83,997
  • 17
  • 205
  • 265
0

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>
Rico Kahler
  • 17,616
  • 11
  • 59
  • 85
  • This does not answer op's question: The question is about redirecting `console.log()` calls from embedded JS code, while your answer explains a bad¹ way of executing javascript code entered by the visitor of the website. ¹ bad: see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_eval! – Iziminza Aug 10 '23 at 09:48