简体   繁体   中英

How to restore / reset window.console.log

I have an application that changes window.console.log to a function.

I want to reset window.console.log back it normal on a certain page, however when I run delete window.console.log; and call console.log('asd'); I get an exception

TypeError: console.log is not a function. (In 'console.log(error)', 'console.log' is undefined)

How do I restore it properly so a certain page can simply console.log normally instead of the custom one I had?

If you're able to access the code from before the application modifies console.log you could do the following:

window.defaultConsoleLog = console.log;

// here would be the code where the application modifies console.log

// calling console.log would now be the modified version from the application:
console.log('Hello');

// calling defaultConsoleLog would now call the original console.log:
defaultConsoleLog.log('Hello');
// OR
window.defaultConsoleLog('Hello');

// you can then reset to the original console.log like this:
console.log = window.defaultConsoleLog;

When you were doing delete window.console.log , this removes the function from the window.console object instead of resetting it.

You can simply store the old native function in an other variable or property and restore it later. For example :

 // Storing the native console.log into a property in window window.oldLog = window.console.log // Overriding the console.log function console.log = (str) => { document.getElementById('logs').textContent += str } console.log('Calling the new console.log') window.oldLog('Calling the old console.log') // Now resetting the native console.log console.log = window.oldLog // Clearing up delete window.oldLog console.log('Calling the restored console.log')
 <pre id="logs"></pre>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM