1

Say I had some JavaScript function which, when run, logged its output in the console - using console.log(). After the function has run, is there a way to make it export the result into the HTML console?

Thanks

1

2 Answers 2

4

You can overwrite the default function with your own function.

(function () {

    // save the original console.log function
    var old_logger = console.log;

    // grab html element for adding console.log output
    var html_logger = document.getElementById('html_logger');

    // replace console.log function with our own function
    console.log = function(msg) {

      // first call old logger for console output
      old_logger.call(this, arguments);

      // check what we need to output (object or text) and add it to the html element.
      if (typeof msg == 'object') {
        html_logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(msg) : msg) + '<br>';
      } else {
        html_logger.innerHTML += msg + '<br>';
      }
    }
})();

Here is a JSFiddle to complete the answer with a working example.

http://jsfiddle.net/djr0mj9p/1/

Sign up to request clarification or add additional context in comments.

Comments

3

You can extend console.log function:

function extendLog(logger) {
    var original = console.log;
    console.log = function() {
        logger(Array.prototype.slice.call(arguments));
        return original.apply(this, arguments);
    }
}

// custom logger
// args - array of arguments passed to console.log
var myLogger = function(args) {
    var log = document.createElement("div");
    log.innerHTML = args;
    document.body.appendChild(log);
}

extendLog(myLogger);

console.log("Hello world!");
console.log("How", "are", "you?");

extendLog function has one argument which is your logging function. You can also call extendLog multiple times with different loggers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.