简体   繁体   English

复制/覆盖javascript的console.log函数

[英]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. 我正在构建Javascript-> Cocoa / Objective-C桥(实际上是一个小测试),这意味着我可以从我的JavaScript代码中调用Objective-C函数。
  • 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. 面临的问题之一是console.log中的message / errors / logs / etc不可见,因此将它们转发到相应的Cocoa函数(我创建了一个类似- (void)log:(NSString*)msg函数,只需将参数作为字符串并在Xcode的控制台窗口中将其打印出来即可。

Now, the thing is how do I replicate 100% what console.log does + forward the message to my own log function? 现在,问题是如何100%复制console.log所做的工作+将消息转发到我自己的log功能?

This is what I've done so far: 到目前为止,这是我所做的:

Javascript 使用Javascript

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

Objective-C 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. 如果在调用console.log("something") ,“ text”是一个简单的文本字符串,则可以正常工作。 If I pass the console.log function an object, then it's not working as expected (eg in Chrome's Javascript console window). 如果我将console.log函数传递给一个对象,则该对象将无法正常工作(例如,在Chrome的Javascript控制台窗口中)。

How would you go about it? 你会怎么做?

Is it possible to get the string output of what console.log would normally print out? 是否有可能得到一个什么样的字符串输出console.log通常打印出来?


PS I tried playing with JSON.stringify(obj, null, 4) a bit, but it still doesn't seem right. PS我试过玩JSON.stringify(obj, null, 4)一点,但它仍然看起来不正确。 Any ideas? 有任何想法吗?

It sounds like you want the original functionality to persist whilst also capturing the input and passing it to your API. 听起来您想保留原始功能,同时还要捕获输入并将其传递给您的API。 That could be achieved by something like (JSFiddle) : 这可以通过(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. 首先,本机console.log可以接收任意数量的参数,因此我们使用arguments来处理。 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. 我们必须使用.apply()console的上下文中调用原始方法,它还允许我们传递与原始调用完全相同的参数。

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

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