Search code examples
javascriptconsoleconsole.log

how can I enable/ disable console.log from the browser console


I have a load of console.logs in my code, but I only need to see them/ turn them on if I need to see them on a site, so I want a way to be able to enable/ disbale them from in browser console by setting up a couple of snippets, such as: adysis.debug('enable') , adysis.debug('disable') but how can i get these to them trigger the console.logs in the code, I got no clue at all at the moment on how to do it?


Solution

  • To disable ALL the console's methods use Proxy.

    Use console.enabled = true/false in the browser console to disable/enable console. The disabled state is persisted in the local storage. So it's the same after a page reload.

    (Remove try/catch since it's not allowed here).

    {
      const key = 'console-enabled';
      
      let enabled;
      try{
      enabled = localStorage.getItem(key);
      }catch(_){}
      
      window.console = new Proxy(window.console, {
        get(console, prop){
          if(prop === 'enabled'){
            return disabled;
          }
          if(!enabled && typeof console[prop] === 'function' && console.hasOwnProperty(prop)){
            return function(){}
          }
          return Reflect.get(...arguments);
        },
        set(console, prop, val){
          if(prop === 'enabled'){
            enabled = val;
            try{
              enabled ? localStorage.setItem(key, val) : localStorage.removeItem(key);
            }catch(_){}
            return true;
          }
          return Reflect.set(...arguments);
        }
      });
    }
    
    
    console.log('disabled');
    console.dir(document.body);
    
    $pre.textContent = 'console.log is enumerable: ' + console.propertyIsEnumerable('log');
    
    console.enabled = true;
    
    console.log('enabled');
    console.dir(document.body);
    <pre id="$pre"></pre>