iOS UIWebView中的Javascript console.log() [英] Javascript console.log() in an iOS UIWebView

查看:117
本文介绍了iOS UIWebView中的Javascript console.log()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用UIWebView编写iPhone / iPad应用程序时,控制台不可见。
这个优秀的答案显示了如何捕获错误,但我也想使用console.log()。

When writing a iPhone / iPad app with a UIWebView, the console isn't visible. this excellent answer shows how to trap errors, but I would like to use the console.log() as well.

推荐答案

我有一个使用javascript记录到apps调试控制台的解决方案。
它有点粗糙,但它确实有效。

I have a solution to log, using javascript, to the apps debug console. It's a bit crude, but it works.

首先,我们在javascript中定义console.log()函数,它打开并立即删除iframe ios-log:url。

First, we define the console.log() function in javascript, which opens and immediately removes an iframe with a ios-log: url.

// Debug
console = new Object();
console.log = function(log) {
  var iframe = document.createElement("IFRAME");
  iframe.setAttribute("src", "ios-log:#iOS#" + log);
  document.documentElement.appendChild(iframe);
  iframe.parentNode.removeChild(iframe);
  iframe = null;    
};
console.debug = console.log;
console.info = console.log;
console.warn = console.log;
console.error = console.log;

现在我们必须使用shouldStartLoadWithRequest函数在iOS应用程序的UIWebViewDelegate中捕获此URL。

Now we have to catch this URL in the UIWebViewDelegate in the iOS app using the shouldStartLoadWithRequest function.

- (BOOL)webView:(UIWebView *)webView2 
shouldStartLoadWithRequest:(NSURLRequest *)request 
 navigationType:(UIWebViewNavigationType)navigationType {

    NSString *requestString = [[[request URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    //NSLog(requestString);

    if ([requestString hasPrefix:@"ios-log:"]) {
        NSString* logString = [[requestString componentsSeparatedByString:@":#iOS#"] objectAtIndex:1];
                               NSLog(@"UIWebView console: %@", logString);
        return NO;
    }

    return YES;
}

这篇关于iOS UIWebView中的Javascript console.log()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆