Log to Firefox Error Console from JavaScript

Viewed 97206

Is it possible to add messages to the built-in error console of Firefox from JavaScript code running in web pages?

I know that I there's Firebug, which provides a console object and its own error console, but I was looking for a quick fix earlier on and couldn't find anything.

I guess it might not be possible at all, to prevent malicious web pages from spamming the log?

9 Answers

If you define a global function that checks for the existence of window.console, you can use Firebug for tracing and still plays nice with other browsers and/or if you turn Firebug's console tracing off:

debug = function (log_txt) {
    if (typeof window.console != 'undefined') {
        console.log(log_txt);
    }
}

debug("foo!");

You cannot write to the console directly from untrusted JavaScript (e.g. scripts coming from a page). However, even if installing Firebug does not appeal to you, I'd recommend checking out Firebug Lite, which requires no installation into the browser (nor, in fact, does it even require Firefox). It's a script which you can include into any web page (even dynamically), which will give you some basic Firebug functionality (such as console.log()).

Yes, you can =P

function log(param){
    setTimeout(function(){
        throw new Error("Debug: " + param)
    },0)
}

//Simple Test:
alert(1)
log('This is my message to the error log -_-')
alert(2)
log('I can do this forever, does not break')
alert(3)

Update to a real function

This is a simple hack, just for fun.

I would just install Firebug and use console.log. If you can't do that, though, you can always throw an error:

throw "foobar";
throw new Error("bazquux");

Of course, this will break you out of the code that you're currently executing, so you can't use it for detailed logging, but if you can work around that I think it's the only way to get something logged out of the box.

AFAIK, it is not possible. But if you are interested in how extensions in Firefox interact with the error console, check this out.

If you're interested, check out a script I wrote -- it's a "cheap" Firebug replacement that doesn't interfere with any normal console (like Safari or Chrome) but does extend it with almost all the Firebug methods:

http://code.google.com/p/glentilities/

Look under the hood and you'll see what I mean by "cheap". :-)

Combine it with YUI or json.org's JSON serializers to sorta replicate console.dir.

Firebug and Firebug Lite are definitely nicer GUIs, but I use my home-grown one all the time to retain logging safely even for production code -- without constant commenting & un-commenting,

Related