最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

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

Share Improve this question asked Dec 12, 2015 at 19:13 M SmithM Smith 4301 gold badge10 silver badges19 bronze badges 1
  • gist.github./waynegraham/5766565 – Ramanlfc Commented Dec 12, 2015 at 19:19
Add a ment  | 

2 Answers 2

Reset to default 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 plete the answer with a working example.

http://jsfiddle/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.

发布评论

评论列表(0)

  1. 暂无评论