简体   繁体   English

如何恢复/重置 window.console.log

[英]How to restore / reset window.console.log

I have an application that changes window.console.log to a function.我有一个将 window.console.log 更改为函数的应用程序。

I want to reset window.console.log back it normal on a certain page, however when I run delete window.console.log;我想在某个页面上将 window.console.log 重置为正常状态,但是当我运行时delete window.console.log; and call console.log('asd');并调用 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?我如何正确恢复它以便某个页面可以正常地简单地使用 console.log 而不是我拥有的自定义页面?

If you're able to access the code from before the application modifies console.log you could do the following:如果您能够在应用程序修改console.log之前访问代码,您可以执行以下操作:

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.当您执行delete window.console.log ,这会从window.console对象中删除该函数而不是重置它。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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