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
2 Answers
Reset to default 4You 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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745131044a4612975.html
评论列表(0条)