Bourne
Bourne

Reputation: 10302

Detecting keyboard presses in UIWebView

I have a UIWebView which I'm using to render styled HTML text. The content in the web view is editable thanks to contentEditable on the div set to true.

I would like to keep intercepting the key presses by the user so that I can keep resizing the UIWebView as the user types. How do I intercept the key-press events?

Upvotes: 0

Views: 1800

Answers (1)

Chahal
Chahal

Reputation: 1005

First define a dummy url

#define kDummyURL @"dummyurl://dummy"

Then in view did load add a javascript

-(void)webViewDidFinishLoad:(UIWebView *)webView{
    [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"$(function(){$('input, textarea').keypress(function() {window.location = \"%@\";});})",kDummyURL]];
}

and in should Start load with request try to capture that dummyurl which will be fired by javascript you just added

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    if ([[request.URL absoluteString] isEqualToString:kDummyURL]) {
        //key is pressed on HTML page, here you can implement what you want
        return NO;
    }
    return YES:
}

Upvotes: 2

Related Questions