Access window.console after overwrite

前端 未结 4 1537
醉话见心
醉话见心 2020-12-10 14:15

Is it possible to somehow access to console.log after it gets overwritten?

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

相关标签:
4条回答
  • 2020-12-10 14:42

    You can back up the console before overwriting it.

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

    Then you can use the oldConsole variable.

    oldConsole.log('test');
    

    If you can't back it up, you can create an iFrame, and then steal the console from there (this may not work in all browsers):

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

    Demo: http://jsfiddle.net/jcG7E/2

    0 讨论(0)
  • 2020-12-10 14:44
    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;
        }
    
    }
    
    0 讨论(0)
  • 2020-12-10 14:45

    It's not possible. Except if whoever has overwritten it has included some code to undo it.

    0 讨论(0)
  • 2020-12-10 14:58

    Edit (2017-04-08): This advise is outdated, in Firefox 52 and Chrome 57 console is no longer defined on the window prototype and deleting it will really delete it.


    At least with the console object defined by Firefox and Chrome, you can simply delete the overwritten property to restore the original one:

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

    This works as if the console property were defined on the prototype of the window object - except that it isn't, the browsers are doing some magic here.

    0 讨论(0)
提交回复
热议问题