代码之家  ›  专栏  ›  技术社区  ›  David Stanton

如何从浏览器控制台启用/禁用console.log

  •  0
  • David Stanton  · 技术社区  · 1 年前

    我的代码中有很多console.log,但如果我需要在网站上看到它们,我只需要看到它们/打开它们,所以我想通过设置几个片段来从浏览器控制台中启用/取消它们,例如:adysis.debug(“启用”)、adysis/debug(“禁用”),但我如何才能让它们触发代码中的console.log,我现在根本不知道该怎么做?

    1 回复  |  直到 1 年前
        1
  •  2
  •   Alexander Nenashev    1 年前

    要禁用控制台的所有方法,请使用 Proxy

    使用 console.enabled = true/false 在浏览器控制台中禁用/启用控制台。 禁用状态将保留在本地存储中。所以页面重新加载后也是一样的。

    (删除 try/catch 因为这里不允许)。

    {
      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>