简体   繁体   中英

Replicating/overriding javascript's console.log function

OK, so here's what I'm trying to do:

  • I'm building a Javascript->Cocoa/Objective-C bridge (a tiny test actually), which means that I'm able to call an Objective-C function from my JavaScript code.
  • One of the issues faced is that messages/errors/logs/etc from console.log are not visible, so they are to be forwarded to the corresponding Cocoa function (i created one like - (void)log:(NSString*)msg which simply takes a parameter as string and prints it out in the Xcode's console window.

Now, the thing is how do I replicate 100% what console.log does + forward the message to my own log function?

This is what I've done so far:

Javascript

console.log = function(text) {
    API.log_(text);
}

Objective-C

- (void)log:(NSString*)msg
{
    NSLog(@"Logging from JS : %@", msg);
}

If "text" is a simple text string when calling console.log("something") , then it works fine. If I pass the console.log function an object, then it's not working as expected (eg in Chrome's Javascript console window).

How would you go about it?

Is it possible to get the string output of what console.log would normally print out?


PS I tried playing with JSON.stringify(obj, null, 4) a bit, but it still doesn't seem right. Any ideas?

It sounds like you want the original functionality to persist whilst also capturing the input and passing it to your API. That could be achieved by something like (JSFiddle) :

var original = console.log,
    API = {
        log_: function() {
            // Your API functionality
        }
    };

console.log = function() {    
    original.apply(console, arguments);
    API.log_(arguments);
};

A couple of things to point out. Firstly, the native console.log can receive any number of parameters, so we use arguments to handle this. We have to use .apply() to call the original method in the context of console and it also allows us to pass the arguments exactly as they were on the original call.

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