简体   繁体   English

如何覆盖console.log

[英]How to override console.log

I am using the following code to override the console.log function, because I want to print console.log only if showConsole returns true . 我使用以下代码来覆盖console.log函数,因为我只想在showConsole返回true时才打印console.log

var proxyConsolelog = window.console.log;


console.log=function(msg){
    try{
        if(Boolean(showConsole))
        {
            proxyConsolelog(msg);
        }
    }catch(e){
        alert(JSON.stringify(e.message));
        proxyConsolelog('ERROR-->>'+e.message);
    }
}

The proxyConsolelog line creates a problem, and alert(JSON.stringify(e.message)); proxyConsolelog行会产生问题,并alert(JSON.stringify(e.message)); is giving me a "Type error". 给我一个“类型错误”。

And I get this: 我得到了这个:

void SendDelegateMessage(NSInvocation *): delegate (webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:) failed to return after waiting 10 seconds. void SendDelegateMessage(NSInvocation *):委托(webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame :)在等待10秒后无法返回。 main run loop mode: kCFRunLoopDefaultMode 主运行循环模式:kCFRunLoopDefaultMode

in the log. 在日志中。

How can I achieve this? 我怎样才能做到这一点?

The problem you have is that the receiver ( this ) when you call your function, isn't the console. 你遇到的问题是,当你调用你的函数时,接收器( this )不是控制台。

You can do this : 你可以这样做 :

var proxyConsolelog = window.console.log.bind(window.console);

If you need to be compatible with IE8 (which doesn't have bind ), you may do this : 如果您需要与IE8(没有bind )兼容,您可以这样做:

var logFun = window.console.log;
var proxyConsolelog = function(){
     logFun.apply(window.console, arguments)
};

As you tagged the question , then you may also use proxy : 当您标记问题 ,您也可以使用代理

var proxyConsolelog = $.proxy(window.console.log, window.console);

Once you have your new function, you can call it just like console.log : 获得新功能后,可以像console.log一样调用它:

proxyConsolelog('some', {arg:'uments'});

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

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