UIWebViewは、HTMLの内容やページ情報の変更を簡単に行えます

2341 ワード

stringByEvaluatingJavaScriptFromStringという方法でiOSでUIWebViewのWeb要素と対話できます.stringByEvaluatingJavaScriptFromStringメソッドを使用すると、UIWebViewのページのロードが完了してから呼び出す必要があります.
UIWebViewを作成し、ロードするURLを
NSURL *url =[[NSURL alloc] initWithString:@"http://www.google.com.hk/m?gl=CN&hl=zh_CN&source=ihp"];

Webviewのエージェントメソッド
- (void)webViewDidFinishLoad:(UIWebView *)webView {    
    //        url
    NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];  
   
   //     title
    NSString *title = [webview stringByEvaluatingJavaScriptFromString:@"document.title"];
   //           
    NSString *js_result = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByName('q')[0].value='iOS  ';"];   
   //     
    NSString *js_result2 = [webView stringByEvaluatingJavaScriptFromString:@"document.forms[0].submit(); "];  
    
}

これによりGoogleでキーワード「iOS開発」を検索することができます.
上記の機能はjsの関数にカプセル化され、この関数をページに挿入して実行できます.
if ([title compare: @"Google"]==NSOrderedSame ) {  
    [webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement_x('script');"    
    //     script   ,type 'text/javascript'
     "script.type = 'text/javascript';" 
     //             ,           :mySearch,      google             
     "script.text = "function mySearch() { "    
     "var field = document.getElementsByName('q')[0];"    
     "field.value='iOS  ';"    
     "document.forms[0].submit();"    
     "}";"    
     "document.getElementsByTagName_r('head')[0].appendChild(script);"];     
      
      //   stringByEvaluatingJavaScriptFromString  mySearch  
    [webView stringByEvaluatingJavaScriptFromString:@"mySearch();"];    
}  

HTMLの内容を取得する
    ID  html   

- (void)webViewDidFinishLoad:(UIWebView *)webView {    
        NSString *js = @"document.getElementById('lg').innerHTML";    
        NSString *pageSource = [webView stringByEvaluatingJavaScriptFromString:js];   

        NSLog(@"pagesource:%@", pageSource); 
}