Skip to content Skip to sidebar Skip to footer

Embed Js Console Within Website

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?

Solution 1:

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.

Solution 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";
    }
};

//testvar test=12345;
console.log('test', 'xyz', test);

Solution 3:

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><formid="console-form"><inputtype="text"id="command"><inputtype="submit"value="Run Command"><buttonid="clear"type="button">Clear</button></form><hr><preid="console"></pre></div>

Post a Comment for "Embed Js Console Within Website"