最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to override console.log - Stack Overflow

programmeradmin1浏览0评论

I am using the following code to override the console.log function, because I want to print console.log only if showConsole returns true.

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)); is giving me a "Type error".

And I get this:

void SendDelegateMessage(NSInvocation *): delegate (webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:) failed to return after waiting 10 seconds. main run loop mode: kCFRunLoopDefaultMode

in the log.

How can I achieve this?

I am using the following code to override the console.log function, because I want to print console.log only if showConsole returns true.

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)); is giving me a "Type error".

And I get this:

void SendDelegateMessage(NSInvocation *): delegate (webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:) failed to return after waiting 10 seconds. main run loop mode: kCFRunLoopDefaultMode

in the log.

How can I achieve this?

Share Improve this question edited Aug 12, 2013 at 15:09 Ry- 226k56 gold badges493 silver badges499 bronze badges asked Aug 12, 2013 at 15:03 Prince Kumar SharmaPrince Kumar Sharma 12.6k4 gold badges62 silver badges90 bronze badges 2
  • Have you tried proxyConsolelog.apply(console, arguments);? – plalx Commented Aug 12, 2013 at 15:09
  • I don't know what's showConsole but I doubt it's useful to do Boolean(showConsole). – Denys Séguret Commented Aug 12, 2013 at 15:46
Add a ment  | 

1 Answer 1

Reset to default 10

The problem you have is that the receiver (this) when you call your function, isn't the console.

You can do this :

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

If you need to be patible with IE8 (which doesn't have bind), you may do this :

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

As you tagged the question jquery, 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 :

proxyConsolelog('some', {arg:'uments'});
发布评论

评论列表(0)

  1. 暂无评论