我在某处阅读以使用
- (void)webView:(WebView *)webView addMessageToConsole:(NSDictionary *)message
来自 UIDelegate 的委托(delegate)方法。但是我需要如何/在哪里将 WebView(不是 UIWebView)的委托(delegate)设置为我的自定义委托(delegate)?
我知道 Apple 不允许在 AppStore 中这样做,但我只是想实现它以用于调试目的。
到目前为止我尝试了什么:
- (void)webView:(id)sender didClearWindowObject:(id)windowObject forFrame:(WebFrame*)frame
{
[webView setUIDelegate:[[MyCustomUIDelegate alloc] init]];
}
和
-(void) webView:(id)webView windowScriptObjectAvailable:(id)newWindowScriptObject
{
[webView setUIDelegate:[[MyCustomUIDelegate alloc] init]];
}
最佳答案
这篇文章可能会帮助你:
How can my iPhone Objective-C code get notified of Javascript errors in a UIWebView?
您可以将 UIWebView 控件连接到隐藏的 WebKit 框架并获取所有异常、执行的函数等。
另一种方式是posted here :将javascript代码注入(inject)到调用objecie-c函数的响应中。
NSString* path = [[NSBundle mainBundle] pathForResource:@"script"
ofType:@"js"];
NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
[sender stringByEvaluatingJavaScriptFromString:content];
例如,javascript 代码可能类似于:
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代码,如:
- (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;
}
关于ios - 为 UIWebView 设置 UIDelegate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8802537/