Setting UIDelegate for UIWebView
我在某处阅读以阅读JavaScript控制台消息,
1 | - (void)webView:(WebView *)webView addMessageToConsole:(NSDictionary *)message |
UIDelegate的委托方法。 但是,如何/在何处将WebView的委托(而不是UIWebView)设置为我的自定义委托?
我知道Apple不允许在AppStore中使用此功能,但我只想实现此功能以用于调试。
到目前为止我尝试过的是:
1 2 3 4 | - (void)webView:(id)sender didClearWindowObject:(id)windowObject forFrame:(WebFrame*)frame { [webView setUIDelegate:[[MyCustomUIDelegate alloc] init]]; } |
和
1 2 3 4 | -(void) webView:(id)webView windowScriptObjectAvailable:(id)newWindowScriptObject { [webView setUIDelegate:[[MyCustomUIDelegate alloc] init]]; } |
这篇文章可以帮助您:
我的iPhone Objective-C代码如何在UIWebView中得到有关Javascript错误的通知?
您可以将UIWebView控件挂接到隐藏的WebKit框架,并获取所有异常,已执行的函数等。
此处发布了另一种方法:将javascript代码注入到调用objecie-c函数的响应中。
1 2 3 4 5 6 7 | NSString* path = [[NSBundle mainBundle] pathForResource:@"script" ofType:@"js"]; NSString* content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL]; [sender stringByEvaluatingJavaScriptFromString:content]; |
例如,JavaScript代码可能像这样:
1 2 3 4 5 6 7 8 9 10 11 12 | 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; |
和Objective-C代码类似:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSString *requestString = [[[request URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; //NSLog(requestString); NSLog(@"Request: %@", requestString); if ([requestString hasPrefix:@"ios-log:"]) { NSString* logString = [[requestString componentsSeparatedByString:@":#iOS#"] objectAtIndex:1]; NSLog(@"UIWebView console: %@", logString); return NO; } return YES; } |