开发者

Determine if Firebug's console.log() was called anywhere on a page

I'd like to be able to programmatically add a class of console to the <body&g开发者_开发问答t; tag if Firebug's console.log() was called anywhere on a page. Then I could put some obnoxious message on the screen to remind me not to deploy code with those statements still in it.

The very similar to Eric Meyer's Diagnostic CSS.

Is it possible?


Hehehe. It's an easy mistake to make, isn't it.

  • Option 1: Always write if(window.console) console.log(...); instead of just console.log(..);
  • Option 2:

    function mydebug(thingtodebug) {
        if(window.console) console.log(thingtodebug);
    }
    

..then always use mydebug() instead of console.log();. You could include an else clause that throws up an alert box if console isn't defined.

  • Option 3:

    if(!window.console) {
        var console={
            log : function() {alert("Don't call console.log");}
        }
    }
    

...this will do pretty much exactly what you're asking.

The trouble is that all these options involve including extra code in your live system just to help you avoid embarrassment. (and of course, it'd be even more embarrassing if you miss that alert box!)

If you want to avoid this, a better solution might be to have a separate script that scans your code for any occurrences of console.log. You could run this script as part of your deployment process.

Hope that helps.


This works for me (using jQuery):

$(document).ready(function() {
  var body = $('body'),
      console = window.console;

  console.debug = function() {
    if (!body.hasClass('console')) {
      body.addClass('console');
      console.debug = oldDebug;
    }
  }

  console.debug('foo');
});

It will only add the class the first time our custom function is called. Then it sets console.debug to the original function. That's the cool thing with javascript, you can override nearly everything :)


It's quite simple. Just override the default console object with your own:

<!DOCTYPE html>
<html>
    <head>
        <title>Console Test</title>
        <script>
            var oldConsole = (typeof window.console === "object") ? window.console : null;
            var console = {
                log: function() {
                    oldConsole.log(arguments);
                    document.body.className = "console";
                    alert('applied class');
                }
            };
        </script>
    </head>
    <body>
        <input type="button" value="click me" onclick="console.log('this is a test');">
    </body>
</html>

Live example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜