ios - 为 UIWebView 设置 UIDelegate

标签 ios uiwebview delegates webkit uikit

我在某处阅读以使用

- (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/

相关文章:

ios - 从 HealthKit 中提取时的额外字符

ios - aws Rekognition 未在 iOS 上初始化

ios - 如何在 iOS 中将本地(文档目录)html 加载到 webview 中?

ios - xcode - 从本地 html 文件加载 UIWebView

ios - 反向关系过滤列表

ios - 在 cellForRowAt 中手动触发 didSelectRowAtIndexPath 会导致实际 didSelectRowAtIndexPath 委托(delegate)方法中的单元格为零

pdf - iOS7 更新 - 在 UIWebView 中加载的 Airprinting PDF 产生缩放 PDF 到字母页面大小的 50%

ios - 为什么我的第一个回复是空的?

c# - 如何像在 C# 中那样在 Java 中使用回调调用函数?

c# - += 委托(delegate)运算符