Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access window.console after overwrite

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

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

Would be it be possible to regain the original console.log functionality?

like image 682
Ilia Choly Avatar asked Aug 16 '11 16:08

Ilia Choly


People also ask

Can you override console log?

log. To override a console method, we just need to redefine how the method is executed. You'll need to wrap your code to prevent the access of other functions to the private (original) method.

What is the console in JavaScript?

The JavaScript console is a command line interface in your browser that can execute snippets of code. When that code snippet is designed to interact with the webpage you are currently on, result can happen that might not have been possible otherwise.

What is console object?

The console object provides access to the browser's debugging console (e.g. the Web console in Firefox). The specifics of how it works varies from browser to browser, but there is a de facto set of features that are typically provided. The console object can be accessed from any global object.


2 Answers

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.

like image 41
Wladimir Palant Avatar answered Oct 21 '22 21:10

Wladimir Palant


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

like image 186
Rocket Hazmat Avatar answered Oct 21 '22 21:10

Rocket Hazmat