8

I have an UIWebView with an <input type="text"/> html element in it. I want to focus the input element in the html and show the keyboard on the iPhone programmatically, without tapping the screen.

I've tried the following:

  • set the focus from JavaScript (in this case the onFocus JS event will fire but the keyboard won't show up)
  • [webView becomeFirstresponder] (returns NO)
  • set the first subview of the webView to be the firstResponder (returns NO)
  • subclass UIWebView to return YES to canBecomeFirstResponder: (nothing happens)

I'm trying to find the solution since yesterday but I couldn't find it. Please help.

Paras Joshi
  • 20,427
  • 11
  • 57
  • 70
user505618
  • 81
  • 1
  • 4
  • did you found some solution for this? The only way I found is to programmatically emulate a click on the WebView. But my app may be rejected because of this... :( – Dmitry Aug 31 '12 at 10:27
  • 2
    Starting with iOS 6 you can use [keyboardDisplayRequiresUserAction](http://developer.apple.com/library/ios/#documentation/uikit/reference/UIWebView_Class/Reference/Reference.html) to do this. – catlan Nov 06 '12 at 16:52
  • I don't know how you managed to create this problem but normally the becomeFirstResponder has to be used like I described it in my article: http://bcaccinolo.wordpress.com/2010/12/28/uitextfield-with-the-keyboard-automagically/ – Benoit Caccinolo Dec 28 '10 at 10:50
  • -1, It doesn't work for UIWebView. – tangqiaoboy Mar 23 '12 at 08:25
  • Have you tried to put the focus method to the onload action of the web page? – Ondrej Rafaj Feb 20 '13 at 15:50
  • try this link http://stackoverflow.com/questions/8474386/uiwebview-with-contenteditable-html-editing-first-responder-handling – Raj Apr 03 '13 at 04:42
  • Try out this answer. It may help you. [UIWebView with contentEditable (html editing), first responder handling?][1] Thanks [1]: http://stackoverflow.com/questions/8474386/uiwebview-with-contenteditable-html-editing-first-responder-handling – Vandana Rao Apr 04 '13 at 04:01

2 Answers2

2

In iOS6 or above, you have to set keyboardDisplayRequiresUserAction to NO first:

- (void)webViewDidFinishLoad:(UIWebView *)webView 
{
    webView.keyboardDisplayRequiresUserAction = NO;
    [webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"theElementId\").setFocus();"]; 
}
OpenThread
  • 2,096
  • 3
  • 28
  • 49
0

Have you tried this? Don't forget to wire up the UIWebView's delegate connection, and ideally execute the javascript only when required.

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"theElementId\").setFocus();"]; 
}
wpearse
  • 2,422
  • 2
  • 29
  • 30