iOS UIWebView 中的 Javascript console.log()

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

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

问题描述

使用 UIWebView 编写 iPhone/iPad 应用程序时,控制台不可见.这很好answer 展示了如何捕获错误,但我也想使用 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 记录到应用程序调试控制台的解决方案.这有点粗糙,但它有效.

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

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

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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:iOS UIWebView 中的 Javascript console.log()

基础教程推荐