Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending all Javascript console output into a DOM element

How does one send all console output into a DOM element so it can be viewed without having to open any developer tools? I'd like to see all output, such as JS errors, console.log() output, etc.

like image 703
John Avatar asked May 17 '13 19:05

John


People also ask

How do I return a value from console log?

console. log(A); Parameters: It accepts a parameter which can be an array, an object or any message. Return value: It returns the value of the parameter given.

Can we use console log in HTML?

The console. log() method in HTML is used for writing a message in the console. It indicates an important message during testing of any program. The message is sent as a parameter to the console.


3 Answers

I found the accepted answer above helpful but it does have a couple issues as indicated in the comments:

1) doesn't work in Chrome because "former" does not take into account the this context no long being the console, the fix is to use the JavaScript apply method.

2) It does not account for multiple arguments being passed to console.log

I also wanted this to work without jQuery.

    var baseLogFunction = console.log;
    console.log = function(){
        baseLogFunction.apply(console, arguments);

        var args = Array.prototype.slice.call(arguments);
        for(var i=0;i<args.length;i++){
            var node = createLogNode(args[i]);
            document.querySelector("#mylog").appendChild(node);
        }

    }

    function createLogNode(message){
        var node = document.createElement("div");
        var textNode = document.createTextNode(message);
        node.appendChild(textNode);
        return node;
    }

    window.onerror = function(message, url, linenumber) {
        console.log("JavaScript error: " + message + " on line " +
            linenumber + " for " + url);
    }

Here is an updated working example with those changes. http://jsfiddle.net/eca7gcLz/

like image 97
Craig McKeachie Avatar answered Sep 30 '22 17:09

Craig McKeachie


This is one approach for a quick solution:

Javascript

var former = console.log;
console.log = function(msg){
    former(msg);  //maintains existing logging via the console.
    $("#mylog").append("<div>" + msg + "</div>");
}

window.onerror = function(message, url, linenumber) {
    console.log("JavaScript error: " + message + " on line " + 
            linenumber + " for " + url);
}

HTML

<div id="mylog"></div>

Working Example http://jsfiddle.net/pUaYn/2/

like image 14
Kevin Bowersox Avatar answered Sep 30 '22 17:09

Kevin Bowersox


Simple console.log redefinition, without error handling:

  const originalConsoleLog = console.log
  console.log = (...args) => {
    args.map(arg => document.querySelector("#mylog").innerHTML += arg + '<br>')
  }
  console.log = originalConsoleLog
like image 1
Damian Pavlica Avatar answered Sep 30 '22 17:09

Damian Pavlica