Search code examples
javascriptdebuggingfirebuggoogle-chrome-devtools

Creating a custom "console" object to interact with Web Console in browser for custom debugger


The Mozilla Developer Network page on the browser-provided Javascript console object says: "Note: At least in Firefox, if a page defines a console object, that object overrides the one built into Firefox.". Is there any way to overwrite this object, but still interact with the browser's Web Console?

A use case is to intercept console.log() calls and do something extra or take different parameters, such as a log classification, while retaining the line number/file information provided when logging to console by tools like Firebug or Google Chrome Inspect Element. The closest matching answer I could find is: Intercepting web browser console messages, but it doesn't dive into interacting with the web console through a custom console object, and using a custom defined debug service like

debug.log = function(string, logLevel) {
    checkLogLevel(logLevel); // return false if environment log setting is below logLevel 
    var changedString = manipulate(string); 
    console.log(changedString); 
}

doesn't retain the line number/file source of the function calling debug.log(). An option is to do something with console.trace() and crawl one level up the trace stack, but I was curious about extending console.log() first. I'd also like to find a solution that works with existing Web Consoles/tools like Firebug rather than creating a custom browser extension or Firebug plugin, but if anybody knows of existing solutions for this I'd be interested in them.

Obviously something like:

    console = {
        log: function (string) {
            console.log('hey!');
        }
    }
    console.log('hey!');

won't work and results in infinite recursion.


Solution

  • It's easy, just save a reference to the (original) console before overwriting it:

    var originalConsole = window.console;
    console = {
        log: function(message) {
            originalConsole.log(message);
            // do whatever custom thing you want
        }
    }