UIWebView 是 iOS SDK 中渲染网面的控件,在显示网页的时候,我们可以 hack 网页然后显示想显示的内容。其中就要用到 javascript 的知识,而 UIWebView 与 javascript 交互的方法就是
stringByEvaluatingJavaScriptFromString:
有了这个方法我们可以通过 objc 调用 javascript,可以注入 javascript。
首先我们来看一下,如何调用 javascript:
[webView stringByEvaluatingJavaScriptFromString:@"myFunction();"];  
这儿 myFunction() 就是我们的 javascript 方法。
再来看看入何注入 javascript,我们先写一个需要注入的 javascript:
function showAlert() {  
   alert('in show alert');  
}  
保存为 test.js,然后拖到 xcode 的 resource 分组下。再用代码在初始化的时候注入这个 js(如在viewDidLoad方法里)。
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"js"];  
NSString *jsString = [[NSString alloc] initWithContentsOfFile:filePath];  
[webView stringByEvaluatingJavaScriptFromString:jsString];  
这样就注入了上面的 js,那么我们可以随时调用 js 的方法,如何调用,上面有介绍。
那么我们能不能通过 js 来调用 objc 的方法呢。 当然可以,原理就是利用 UIWebView 重定向请求,传一些命令到我们的 UIWebView,在 UIWebView 的 delegate 的方法中接收这些命令,并根据命令执行相应的 objc 方法。这样就相当于在 javascript 中调用 objc 的方法。说起来有点抽象,看看代码一下就明白。
首先我们写一个 javascript 方法如下:
function sendCommand(cmd,param){  
    var url="testapp:"+cmd+":"+param;  
    document.location = url;  
}  
function clickLink(){  
    sendCommand("alert","你好吗?");  
}  
然后在你的 html 里调用这个 js 方法 如:
<input type="button" value="Click me!" onclick="clickLink()" /><br/>  
最后我们在 UIWebVew 中截获这个重定向请求:
#pragma mark --  
#pragma mark UIWebViewDelegate  
 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {  
      
    NSString *requestString = [[request URL] absoluteString];  
    NSArray *components = [requestString componentsSeparatedByString:@":"];  
    if ([components count] > 1 && [(NSString *)[components objectAtIndex:0] isEqualToString:@"testapp"]) {  
      if([(NSString *)[components objectAtIndex:1] isEqualToString:@"alert"])   
        {  
            UIAlertView *alert = [[UIAlertView alloc]   
                                  initWithTitle:@"Alert from Cocoa Touch" message:[components objectAtIndex:2]  
                                  delegate:self cancelButtonTitle:nil  
                                  otherButtonTitles:@"OK", nil];  
            [alert show];  
       }  
       return NO;  
    }  
    return YES;  
}