简体   繁体   中英

Is there a way to print the console log from JavaScript, into HTML?

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

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/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM