2

I've used the method described here at Stack Overflow to intercept the console log, but I'm unable to get the object so sent together with a text. Consider the following code:

var obj={result:true,type:"text"};

(function(){
    var oldLog = console.log;
    console.log = function (message) {
        alert(message);  // message does not return the object
        oldLog.apply(console, arguments);

    };
})();

console.log("hi",obj);

What have I to write in place of message in the alert code line to get the obj object?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
tic
  • 4,009
  • 15
  • 45
  • 86

2 Answers2

2

You are passing multiple arguments into your custom console.log function, but you are only calling alert on the first argument. To fix this, iterate over the arguments to your custom console.log function, and call alert on each of the arguments:

var obj={result:true,type:"text"};

(function(){
    var oldLog = console.log;
    console.log = function () {
        for (var i = 0; i < arguments.length; i++) {
            alert(arguments[i]);
        }
        oldLog.apply(console, arguments);

    };
})();

console.log("hi",obj);

If you want to have only one alert that displays all the objects, then you can concatenate their string representations in the for loop and call alert only once at the end:

var obj={result:true,type:"text"};

(function(){
    var oldLog = console.log;
    console.log = function () {
      var result = "";  
        for (var i = 0; i < arguments.length; i++) {
            result += arguments[i] + " ";
        }
        alert(result);
        oldLog.apply(console, arguments);

    };
})();

console.log("hi",obj);

And finally, if you want to see the contents of the object in your alert, you can call JSON.stringify() on each argument before it gets processed.

Maximillian Laumeister
  • 19,884
  • 8
  • 59
  • 78
  • Great, now every console call is replaced with not one, but *n* blocking function calls! :) *(The solution is of course correct, technically, but sometimes asking* why *is just as important)* – doldt Jul 18 '15 at 21:57
  • @doldt Edited my answer to add a version that alerts once for all the objects. Perhaps this is closer to what you were looking for! – Maximillian Laumeister Jul 18 '15 at 22:01
2

you can try this

var obj={result:true,type:"text"};

(function(){
    var oldLog = console.log;
    console.log = function () {

            alert(JSON.stringify(arguments));

        oldLog.apply(console, arguments);

    };
})();
m4n0
  • 29,823
  • 27
  • 76
  • 89
abs
  • 801
  • 6
  • 15