Skip to content Skip to sidebar Skip to footer

Type In String On Website Programmatically

I'd wanted to know how or whether I can type in something in a textField on a website from my iPhone application code. So I want to go to a website where is one textField in the mi

Solution 1:

You can inject JavaScript into an UIWebView by calling the method stringByEvaluatingJavaScriptFromString. You write a piece of JavaScript where you select the input field and modify it's value attribute.

The method is described here: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWebView_Class/index.html#//apple_ref/occ/instm/UIWebView/stringByEvaluatingJavaScriptFromString:


There actually is an article on the web that explains how to do just what you need: http://iphoneincubator.com/blog/windows-views/how-to-inject-javascript-functions-into-a-uiwebview/

The following is the part you should use (you just have to change the ID in the DOM selector):

[webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');""script.type = 'text/javascript';""script.text = \"function myFunction() { "
                            "var field = document.getElementById('field_3');"
                            "field.value='Calling function - OK';"
                         "}\";""document.getElementsByTagName('head')[0].appendChild(script);"];

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

Solution 2:

You can inject javascript from your delegate. For instance, in Obj-C (I don't know swift good enough yet) :

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [_webView stringByEvaluatingJavaScriptFromString:@"doSomeStuff()"];
}

In your case, you'll want to manipulate the DOM to add some text in your textfield - something like this :

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    NSString * javascript_code = @"document.querySelector('input[name=your_input_name]').value = 'Foobaz'";
    [_webView stringByEvaluatingJavaScriptFromString:javascript_code];
}

Beware of querySelector though, I'm not sure about its availability in iOS's webview.

Post a Comment for "Type In String On Website Programmatically"