2012-01-10 84 views
1

我读的地方使用从UIDelegate的设置UIDelegate为UIWebView的

- (void)webView:(WebView *)webView addMessageToConsole:(NSDictionary *)message 

委托方法来读取的JavaScript控制台消息。但是,我需要如何/在哪里设置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]]; 
} 
+0

UIDelegate是MacOS的SDK的一部分,而不是iOS的。你想在MacOS或iOS上做到这一点? – MyztikJenz 2012-01-19 01:41:25

+0

Owh ..我试图在iOS中这样做,以获取UIDelegate收到的日志消息,有没有办法在iOS上执行此操作?我试过scriptdebugdelegate,但没有给console.log消息。 – Thys 2012-01-19 08:06:45

回答

4

这篇文章可以帮助你:

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

您可以挂钩的UIWebView控制隐藏的WebKit框架和获取所有异常,执行的功能和类似功能。

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

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

[sender stringByEvaluatingJavaScriptFromString:content]; 

为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; 
} 
+0

它使用ScriptDebugDelegate并且不允许实际看到错误/日志消息。 – Thys 2012-01-19 11:30:57

+0

我编辑了我的回复以添加另一种方式。如果您可以编辑网页,则不需要所有员工。 – Esepakuto 2012-01-20 00:53:04

+1

你添加的代码是我试图避免的。但+1的努力:) – Thys 2012-01-20 10:22:19

相关问题