how to intercept Button click inside UIWebview on IOS?

I have a HTML form that has certain fields which i am opening inside a UIWebview. On click of a particular button i want to do a in app action.

The approach i'm using now is on click of the button i redirect the page to a dummy URL. I sniff the URL using delegate method "shouldStartLoadWithRequest" and stop the redirection. I then do my custom event (capture image and upload) and then continue. This seems to be an ugly hack. Anyway i can directly hook into the button click event rather than a page redirection?

UPDATE There seems to be no way to setup a delegate method to fire when a JS function is called on button click. The only way to do this is to use the URL sniffing method mentioned above. This has been explained in detail by joern below, so I will accept his answer.


Solution 1:

You can do the following:

In your HTML

<a class="yourButton" href="inapp://capture">Button Text</a>

In your UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
   if ([request.URL.scheme isEqualToString:@"inapp"]) {
      if ([request.URL.host isEqualToString:@"capture"]) {
         // do capture action
      }  
      return NO;
   }  
   return YES;
}

I added "capture" to your button's URL so that you could distinguish between several buttons that should trigger different actions (if you want to):

Solution 2:

This code:

<a class="yourButton" href="inapp://capture">Restart</a>

doesn't work for me.

I've added "inapp://capture" in my javascript code for event function

KeyboardInputManager.prototype.restart = function (event) {
  window.location.href = "inapp://capture";
  //other code
};

Also I use the UIWebViewDelegate and It works for iOS 8, 9.