2012-04-06 77 views
2

如何在使用UIWebView自動填充數據時使用RegsEx查找登錄表單?在UIWebView中打開的HTML頁面中自動填充用戶名和密碼

我用下面的代碼來獲取所有表單數據:

int NoOfForms = [[self.browser stringByEvaluatingJavaScriptFromString:@"document.forms.length"] intValue]; 

NSMutableArray *formData = [[NSMutableArray alloc] initWithCapacity:0]; 

for (int i = 0 ; i < NoOfForms ; i++) 
{ 
    // total number of elements in each form 
    int elementsInForm = [[self.browser stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.forms[%d].elements.length",i]] intValue]; 
    for (int j = 0; j < elementsInForm; j++) 
    { 
     // element id of each element 
     NSString *elementID = [NSString stringWithFormat:@"document.forms[%d].elements[%d].id",i,j]; 
     // element value of each element 
     NSString *elementValue = [NSString stringWithFormat:@"document.forms[%d].elements[%d].value",i,j]; 

     // dictionary for all values of each element 
     NSDictionary *elementData = [NSDictionary dictionaryWithObjectsAndKeys: 
            [NSNumber numberWithInt:i],@"form No", 
            [NSNumber numberWithInt:j],@"element No", 
            [self.browser stringByEvaluatingJavaScriptFromString:elementID],@"elementID", 
            [self.browser stringByEvaluatingJavaScriptFromString:elementValue],@"elementValue",nil]; 

     // add each element data to a mutable array. 
     [formData addObject:elementData]; 
    } 
} 

,並具有以下代碼來將數據返回到各自的領域:

for (int i = 0 ; i < [dataArray count]; i++) 
{ 
    NSDictionary *elementDict = [dataArray objectAtIndex:i]; 

    int formNumber = [[elementDict objectForKey:@"form No"] intValue]; 
    int elementNumber = [[elementDict objectForKey:@"element No"] intValue]; 
    NSString *formElementID = [elementDict objectForKey:@"elementID"]; 
    NSString *formElementValue = [elementDict objectForKey:@"elementValue"]; 

    if ([[self.browser stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.forms[%d].elements[%d].id",formNumber,elementNumber]] isEqualToString:formElementID]) 
    { 
      [self.browser stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.forms[%d].elements[%d].value='%@'",formNumber,elementNumber,formElementValue]]; 
    } 

} 

現在我只想提交登錄形式..如何找到它?

我遇到了另一個問題:當我的代碼將密碼放入其字段時,一些網站(如mail.google.com)確實會讓這種情況發生,即清空密碼字段。如何解決這個問題呢 ?

更新:目前我已經能夠在mail.google.com上登錄,但無法在belleandclive.com上完成相同的操作。本網站是否爲其登錄表單實施任何安全措施?

回答

2

我想你可以根據表單數據或表單ID判斷哪個是登錄表單,對不對?

所以,如果登錄表單id爲login-form,可以使用下面的代碼提交:

NSString * js = @"document.getElementById('login-form').submit()"; 
[self.webview stringByEvaluatingJavaScriptFromString:js]; 

,或者你可以透過根據表格數據,索引登錄表單通過評審的形式:

int index = ....// your judge code to get index 
NSString * js = [NSString stringWithFormat:@"document.forms[%d].submit()", index]; 
[self.webview stringByEvaluatingJavaScriptFromString:js]; 
相關問題