Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keyboard "done" button pressed event for UIWebView and WKWebView

There are resources for this when using UITextView. How do I register for the Done key button press event? The keyboard shows up when the user focuses a form inside the webview.

like image 540
Maximus S Avatar asked Sep 13 '15 21:09

Maximus S


2 Answers

The main idea is to use Javascript injection to achieve what you want. You can try catching the DOM event called onfocusout (Refer to http://www.w3schools.com/jsref/event_onfocusout.asp for more details).

Following is the example of how you could do it for UIWebView. WKWebView can be handled in a similar way.

Call this to inject some Javascript code after the first time your webview loaded

[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('youTextFieldID').addEventListener('onfocusout', function () {"
                                                @"var frame = document.createElement('iframe');"
                                                @"frame.src = 'doneEditing://';"
                                                @"document.body.appendChild(frame);"
                                                @"setTimeout(function () { document.body.removeChild(frame); }, 0);"
                                                @"}, false);"];

Write your UIWebView delegate method like this

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
        if ([request.URL.scheme isEqualToString:@"doneEditing"]) {
            // Call you event handler here
            [self doneButtonTouchEventHandler]
            return NO;
        }
        return YES;
}

Good luck

like image 116
Ducky Avatar answered Sep 21 '22 01:09

Ducky


The key is to add event listeners when the web page loads. I assume that you want to know about the blur event of a text field.

Here is a basic working example:

<html>
<head>
<script>

    function initPage() {
        document.addEventListener('focusin', handleFocusIn);
        document.addEventListener('focusout', handleFocusOut);
    }

    function handleFocusIn(e) {
        alert('In');
    }

    function handleFocusOut(e) {
        alert('Out');
    }

</script>
</head>

<body onload="initPage()">

<form>
    <input type="text" name="username">
</form>

</body>
</html>

I hope that helps, please let me know otherwise!

Good luck!

like image 29
Sheamus Avatar answered Sep 18 '22 01:09

Sheamus