Home Disable JavaScript console on production
Post
Cancel

Disable JavaScript console on production

I love to put a log of debugging information in my code. Especially in JavaScript part. It shows me a lot of stuff during my work and allows to diagnose what had happened. Moreover I can include tracing/measure/etc using time and profile functions. But all above logs shouldn’t be visible on production to every user.

The solution for above is simple. we need to override window.console functions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
(function () {
    var method;
    var noop = function noop() { };
    var methods = [
    'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
    'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
    'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
    'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];
		console[method] = noop;
    }
}());

If I forgot about something in window.console object, just let me know.

@Cover from WAToday

This post is licensed under CC BY 4.0 by the author.