【问题标题】:Access window.console after overwrite覆盖后访问window.console
【发布时间】:2011-10-28 05:28:36
【问题描述】:

console.log 被覆盖后是否可以通过某种方式访问​​它?

window.console = { log: function (msg) { alert(msg); }, /* etc... */ };

能否恢复原来的 console.log 功能?

【问题讨论】:

  • 原文是什么?萤火虫?

标签: javascript console


【解决方案1】:

您可以在覆盖之前备份控制台。

var oldConsole = window.console;
window.console = { log:function(msg){alert(msg)} //...};

然后你可以使用oldConsole 变量。

oldConsole.log('test');

如果无法备份,可以创建 iFrame,然后从那里窃取控制台(这可能不适用于所有浏览器):

var i = document.createElement('iframe');
i.style.display = 'none';
document.body.appendChild(i);
window.console = i.contentWindow.console;

演示:http://jsfiddle.net/jcG7E/2

【讨论】:

  • 下面的答案(删除window.console)比较有用。我想说这应该是这个问题的公认答案。
  • @RocketHazmat 从 iframe 中窃取控制台的想法是一个相当不错的 hack!
  • iFrame 的解决方案是史诗般的,正是我所需要的。谢谢!
【解决方案2】:

编辑 (2017-04-08):此建议已过时,在 Firefox 52 和 Chrome 57 中 console 不再在窗口原型上定义,删除它会真正删除它。


至少使用Firefox和Chrome定义的console对象,你可以简单地删除被覆盖的属性来恢复原来的:

window.console = {};
delete window.console;
window.console.log("This works!");

这就像 console 属性是在 window 对象的原型上定义的一样工作 - 除了它不是,浏览器在这里做了一些魔法。

【讨论】:

  • 这似乎不适用于最新版本的 Chrome。
  • @RelaXNow:确实,此建议已过期。我对此添加了注释。
【解决方案3】:

这是不可能的。除非覆盖它的人包含了一些撤消它的代码。

【讨论】:

    【解决方案4】:
    var customLog = {
        oriLog: '',
        Log: function(){
            // create string to display
            var displaystring = '';
            for (var i = 0, len = arguments.length; i < len; i++) {
                displaystring += arguments[i];
                if (i + 1 != len) 
                    displaystring += ', ';
            }
            alert(displaystring);
            customLog.oriLog(arguments);
        }
    }
    window.onload = function(){
        if (console != null) {
            customLog.oriLog = console.log;
            console.log = customLog.Log;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-16
      • 2012-03-07
      • 2019-10-13
      相关资源
      最近更新 更多