Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 574
B K Avatar asked Jun 12 '12 07:06

B K


3 Answers

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):

like image 174
joern Avatar answered Nov 08 '22 03:11

joern


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.

like image 27
Kiryl Belasheuski Avatar answered Nov 08 '22 03:11

Kiryl Belasheuski


For swift 4.2

Button code in HTML side:

<a class="catch-iOS" href="inapp://home">Продолжить покупки</a>

UIWebViewDelegate method:

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
    if request.url?.scheme == "inapp" {
        if request.url?.host == "home" {
            // do something
        }
    }
    return true
}
like image 1
akonoplev Avatar answered Nov 08 '22 03:11

akonoplev