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 middle and there I would like to type in a specific string. How can I do that in Swift (or Objective-C - I'll figure out how it works in Swift then)? I would really much appreciate any help :)
2 Answers
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();"];

- 3,326
- 20
- 22
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.

- 10,603
- 3
- 45
- 71
-
Maybe I should have mentioned that I actually don't have a web view but only the html data from the website. But does it even work without using a webView? – borchero Oct 29 '14 at 09:46
-
@OliverBorchert You mean, you have a huge string with all the HTML inside it? What are you doing with this? – Maen Oct 29 '14 at 09:56
-
Well, at the moment I actually don't know how to do this - that's why I have another question on stack overflow how to get information from this - lol. When you want to have a look: [link](http://stackoverflow.com/questions/26626984/convert-html-string-to-something-useful-in-swift?noredirect=1#comment41863517_26626984) – borchero Oct 29 '14 at 10:01