1. 程式人生 > >UIWebView中獲取網頁輸入框的內容

UIWebView中獲取網頁輸入框的內容

一、首先想要獲取UIWebView中的URL 的JavaScript程式碼 :

  • (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSString *jsToGetHTMLSource = @”document.getElementsByTagName(‘html’)[0].innerHTML”;

    NSString *HTMLSource = [self.webView stringByEvaluatingJavaScriptFromString:jsToGetHTMLSource];
    NSLog(@”---------JavaScript原始碼:%@-------”,HTMLSource);
    }

二、在新增UIWebView的頁面的viewDidLoad方法中 設定監聽鍵盤的彈出和隱藏,來達到監聽UIWebView中的input 控制元件的輸入值,設定監聽後 實現監聽方法即可。

  • (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
    }

三、在需要獲取UIWebView中的輸入框 或其它控制元件的值的地方 使用以下程式碼即可,UIWebVIew的控制元件程式碼如:

  • (void)keyboardWillHide:(NSNotification *)notification
    {
    NSString *string = [self.webView stringByEvaluatingJavaScriptFromString:@”document.getElementById(‘input’).value;” ];
    NSLog(@”~~監控的控制元件的值:~~~~:%@”, string);
    }

四、最後不要忘記在頁面要消失的時候移除監聽哦

-(void)resignForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillHideNotification
object:nil];
}