为UIWebView设置UIDelegate

时间:2012-01-10 11:28:00

标签: ios uiwebview delegates webkit uikit

我在某地阅读使用

阅读javascript控制台消息
- (void)webView:(WebView *)webView addMessageToConsole:(NSDictionary *)message

来自UIDelegate的委托方法。但是我需要如何/在哪里将WebView(而不是UIWebView)的委托设置为我的自定义委托?

我知道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]];
}

1 个答案:

答案 0 :(得分:4)

这篇文章可以帮到你:

How can my iPhone Objective-C code get notified of Javascript errors in a UIWebView?

您可以将UIWebView控件挂钩到隐藏的WebKit框架,并获取所有异常,执行的函数等。

另一种方法是posted here:将javascript代码注入到调用objecie-c函数的响应中。

NSString* path = [[NSBundle mainBundle] pathForResource:@"script" 
                                                 ofType:@"js"];
NSString* content = [NSString stringWithContentsOfFile:path
                                              encoding:NSUTF8StringEncoding
                                                 error:NULL];

[sender stringByEvaluatingJavaScriptFromString:content];

for exapmle 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;
}