简体   繁体   中英

Filling out a form and submitting in a UIWebView

I want to fill in a text box inside a UIWebView, so I am using the following code to do so;

NSString *inputipjavascript = [NSString stringWithFormat:@"document.getElementById('IP').value = '%@';", enterip];

NSString *result;
[webView stringByEvaluatingJavaScriptFromString:inputipjavascript];
result = [webView stringByEvaluatingJavaScriptFromString:@"$('#GD').click();"];

The page which has the form on which I want to fill out automatically and submit is:

http://www.whatismyip.com/tools/ip-address-lookup.asp

The above code doesn't work at all, what do I need to do?

The most likely explanation based on the limited details of the context of your code, is that you are ignoring the asynchronous nature of the loadRequest: method and trying to execute your javascript commands before the DOM has loaded. Thus executing your commands on nothing. The UIWebView way to handle this is to use the -(void)webViewDidFinishLoad:(UIWebView *)webView; delegate method.

Edit: To "I did this already, but it didn't work.".

After examining the page at your link: http://www.whatismyip.com/tools/ip-address-lookup.asp . Your javascript is not compatible with the elements of your target webpage. For example here is the tag of the IP input field.

<input type="text" name="IP" value="xxx.xxx.xxx.xxx">

And you are trying to use getElementById('IP') to get access to it. It has no id element so you are not referencing anything. The most precise specifier is the name element, it's value being IP . The first method that came to mind was getElementsByName() , then I just have to use element [0] .

For a quick test I threw a few lines in an IBAction for a test and they worked for me:

- (IBAction)enterAndPress:(id)sender {
    NSString *enterip = @"74.125.227.50"; // take that google
    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementsByName('IP')[0].value = '%@';",enterip]];
    [self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByName('GL')[0].click();"];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM