53

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?

Torsten Marek
  • 83,780
  • 21
  • 91
  • 98

8 Answers8

47

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!");
Tobias Helbich
  • 447
  • 14
  • 32
petsounds
  • 471
  • 4
  • 3
  • +1 this is useful if you accidentally leave console.log's in your production code. – Justin Tanner Sep 16 '11 at 02:33
  • 16
    It is not necessary to wrap the console.log function. By wrapping it you will loose the formating functionality. Just assign it to a debug function: `var debug = function () {} ; if (window.console != undefined) { debug = console.log; }`. Now you can also do this: `debug ("%s", "a")` – ceving Dec 05 '11 at 16:35
  • 1
    @ceving: do you know why with your solution in chrome I get: `TypeError: Illegal invocation` ? – Ruggero Turra May 29 '12 at 10:04
  • @wiso: Chrome might require a wrapper. See here: http://stackoverflow.com/questions/8159233/typeerror-illegal-invocation-on-console-log-apply – ceving May 29 '12 at 13:06
33

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Fabiano Soriani
  • 8,182
  • 9
  • 43
  • 59
33

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()).

Ben Blank
  • 54,908
  • 28
  • 127
  • 156
  • And in the *SeaMonkey* browser (which is also *Gecko*-based), you can enable logging to the JavaScript console via `browser.dom.window.console.enabled` hidden preference (since 2.11, see [bug 739965](https://bugzilla.mozilla.org/show_bug.cgi?id=739965)). This doesn't affect *FireBug*, as all `console.log(...)` results immediately appear in its console regardless of the pref. – Bass Feb 11 '16 at 15:15
14

window.console is undefined in Firefox 4 beta 6 even if Firebug 1.6X.0b1 is enabled and open, probably because of privilege issues that others discuss. However, Firefox 4 has a new Tools > Web Console, and if this is open you have a window.console object and untrusted JavaScript code on the page can use console.log(). The Web Console is in flux (see https://wiki.mozilla.org/Firefox/Projects/Console), you may need to change settings named devtools.* in about:config , YMMV.

skierpage
  • 2,514
  • 21
  • 19
6

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Brian Campbell
  • 322,767
  • 57
  • 360
  • 340
  • I'm not against installing Firebug (which I have by now), I just wanted to know for sure. Throwing an error explictly wasn't an option, because I was tracing my code. – Torsten Marek Apr 23 '09 at 22:05
  • 2
    If you want a non-blocking error message (e.g., monitoring a variable in a loop), use setTimeout("throw new Error('Wheeeeeeee!')",0); – Kevin L. Dec 15 '09 at 20:09
  • 2
    bazquux is EXACTLY the type of error I wanted to notify myself about – bobobobo Jan 18 '10 at 04:30
3

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ólafur Waage
  • 68,817
  • 22
  • 142
  • 198
  • +1 for Components.utils.reportError - I keep forgetting how it's call and wasting time to find it again, over and over again! – Stefano Sep 07 '11 at 11:40
2

This function does not require any extension nor library. However it grants full privileges to the relevant website. No worries since you are the one developing it, right?


// Define mylog() function to log to Firefox' error console if such a
// thing exists
function defineMyLog()
{
    // Provide a useless but harmless fallback
    mylog = function(msg) { };
    // return; // disable in production

    if (typeof(netscape) === "undefined") {
        // alert("Logging implemented only for Firefox");
        return;
    }
    // The initial auth popup can be avoided by pre-setting some magic user_pref
    //  ( "capability.principal.codebase.p0.granted", "UniversalXPConnect"), etc.
    try {
        netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
    } catch (e) { // User has denied privileges
        // alert(e.name + ": " + e.message);
        return;
    }
    ffconsoleService = Components.classes["@mozilla.org/consoleservice;1"]
                                 .getService(Components.interfaces.nsIConsoleService);
    mylog = function (msg)
    {
        netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
        ffconsoleService.logStringMessage(new Date().toLocaleTimeString() + ": " + msg);
    }
    mylog("Firefox logging function has been defined");

    // window.open("javascript:"); // this URL does not work anymore?
}
MarcH
  • 18,738
  • 1
  • 30
  • 25
  • This throws a permissions error in Firefox 4: 'Permission denied to get property XPCComponents.classes'. – jamesmortensen Jun 30 '11 at 20:44
  • Thanks for the feedback jmort253. Did you try to grant the capability in user_pref as demonstrated in a comment in the code? – MarcH Aug 04 '11 at 10:15
  • That was a long time ago so I don't exactly recall... I think you can see it in Firebug. You're probably right about the user_pref needing to be set, but that would mean the log could only be useful to the developer. It's hard to get users to change things like that. – jamesmortensen Aug 06 '11 at 16:18
  • 1
    Even with Firefox 3 this function required to grant full privileges to the website, which definitely makes it useful to the developers only, there is no question about that. I guess they just hardened the security in Firefox 4, which makes sense considering how many users click "OK" without reading. – MarcH Aug 08 '11 at 10:16
  • Ok, I see the value in it as a developer on the local machine. At first I was thinking that the logging system would run on regular users system and not just developers. I've seen some pretty crazy things happen in users browsers and it would be awesome if they could send me a log. I had a bug in something on a coworkers computer I couldn't replicate, until we determined it was because he had NoScript and Adblock Firefox extension installed, which prevented my JS from running! – jamesmortensen Aug 10 '11 at 04:47
1

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,

pluckyglen
  • 819
  • 7
  • 9