关闭控制台中的广告输出/错误

Turn Off Ad Output / Errors In Console

我们正在我们的网站上展示 Google Adwords 广告。让我一直恼火的是,广告将 运行 错误或正常 console.log() 输出,并且该文本出现在我们的控制台中。我想知道是否可以通过 Adword 脚本或 Javascript 关闭这些错误。

广告出现在 iframe 中。

您可以重新定义 console.log 输出:

var oldConsole = console;
console = {
    log: function(str,goOut = false) {
     if (goOut) {
           oldConsole.log(str);
        }
    },
    warn: function(str,goOut = false) {
     if (goOut) {
            oldConsole.warn(str);
        }
    },
    error: function(str,goOut = false) {
     if (goOut) {
            oldConsole.error(str);
        }
    }
}

console.log("this will not appear");
console.log("This will appear",true);

将console对象保存到oldConsole可以让你仍然实际输出到console,然后重新定义console对象可以改变功能。

使用这个函数,要实际输出一些东西,你需要将 TRUE 作为第二个参数,默认情况下不会这样做,到你所有的 console.log 输出,以便它实际出现。

请注意,这正是正在发生的事情:

  1. 将对控制台的引用保存到变量 oldConsole
  2. 将控制台重新定义为一个新对象。
  3. 将其日志、警告和错误的属性设置为我们自己的函数。
  4. 第二个参数 goOut 默认设置为 FALSE,这意味着调用 console.log("hello") 会导致 goOut 为 false(未定义)。
  5. 当您明确将其设置为 true 时,调用 oldConsole.log(str,true) 实际输出到日志。