(转)UIWebView与JavaScript的那些事儿

UIWebView是IOS SDK中渲染网面的控件,在显示网页的时候,咱们能够hack网页而后显示想显示的内容。其中就要用到javascript的知识,而UIWebView与javascript交互的方法就是stringByEvaluatingJavaScriptFromString:javascript

有了这个方法咱们能够经过objc调用javascript,能够注入javascript。html

首先咱们来看一下,如何调用javascript:java

 

  1. [webView stringByEvaluatingJavaScriptFromString:@"myFunction();"];  


这儿myFunction()就是咱们的javascript方法。git

 

再来看看入何注入javascript,咱们先写一个须要注入的javascript:github

 

  1. function showAlert() {  
  2.     alert('in show alert');  
  3. }  


保存为test.js,而后拖到xcode 的resource分组下。再用代码在初始化的时候注入这个js(如在viewDidLoad方法里)。web

 

 

  1. NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"js"];  
  2. NSString *jsString = [[NSString alloc] initWithContentsOfFile:filePath];  
  3. [webView stringByEvaluatingJavaScriptFromString:jsString];  


这样就注入了上面的js,那么咱们能够随时调用js的方法,如何调用,上面有介绍。xcode

 

 

那么咱们能不能经过js来调用objc的方法呢。 固然能够,原理就是利用UIWebView重定向请求,传一些命令到咱们的UIWebView,在UIWebView的delegate的方法中接收这些命令,并根据命令执行相应的objc方法。这样就至关于在javascript中调用objc的方法。提及来有点抽象,看看代码一下就明白。app

首先咱们写一个javascript 方法以下:google

  1. function sendCommand(cmd,param){  
  2.     var url="testapp:"+cmd+":"+param;  
  3.     document.location = url;  
  4. }  
  5. function clickLink(){  
  6.     sendCommand("alert","你好吗?");  
  7. }  

 

而后在你的html里调用这个js方法 如:lua

 

  1. <input type="button" value="Click me!" onclick="clickLink()" /><br/>  


最后咱们在UIWebVew中截获这个重定向请求:

 

 

  1. #pragma mark --  
  2. #pragma mark UIWebViewDelegate  
  3.   
  4. - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {  
  5.       
  6.     NSString *requestString = [[request URL] absoluteString];  
  7.     NSArray *components = [requestString componentsSeparatedByString:@":"];  
  8.     if ([components count] > 1 && [(NSString *)[components objectAtIndex:0] isEqualToString:@"testapp"]) {  
  9.         if([(NSString *)[components objectAtIndex:1] isEqualToString:@"alert"])   
  10.         {  
  11.             UIAlertView *alert = [[UIAlertView alloc]   
  12.                                   initWithTitle:@"Alert from Cocoa Touch" message:[components objectAtIndex:2]  
  13.                                   delegate:self cancelButtonTitle:nil  
  14.                                   otherButtonTitles:@"OK", nil];  
  15.             [alert show];  
  16.         }  
  17.         return NO;  
  18.     }  
  19.     return YES;  
  20. }  



 

看了代码是否是清楚得不能再清楚了呀?  我想phonegap可能与是这样实现的,没去研究过。 不过有一个开源工程你们能够看看,它容许javascript调用objective_c的方法。叫jsbridge-to-cocoa

http://code.google.com/p/jsbridge-to-cocoa/

还有两个相关工程

WebViewJavascriptBridge 与 GAJavaScript 值得你们慢慢研究。