简体   繁体   English

如何截取IOS上的UIWebview内的Button点击?

[英]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. 我有一个HTML表单,其中包含我在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. 我现在使用的方法是单击按钮,我将页面重定向到虚拟URL。 I sniff the URL using delegate method "shouldStartLoadWithRequest" and stop the redirection. 我使用委托方法“shouldStartLoadWithRequest”嗅探URL并停止重定向。 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. 更新当按钮单击调用JS函数时,似乎无法设置要触发的委托方法。 The only way to do this is to use the URL sniffing method mentioned above. 唯一的方法是使用上面提到的URL嗅探方法。 This has been explained in detail by joern below, so I will accept his answer. 这个已经由joern在下面详细解释过,所以我会接受他的回答。

You can do the following: 您可以执行以下操作:

In your HTML 在您的HTML中

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

In your UIWebViewDelegate 在您的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): 我将“捕获”添加到按钮的URL中,以便您可以区分应该触发不同操作的几个按钮(如果您愿意):

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 我在我的javascript代码中为事件函数添加了“inapp:// capture”

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

Also I use the UIWebViewDelegate and It works for iOS 8, 9. 我也使用UIWebViewDelegate,它适用于iOS 8,9。

For swift 4.2 对于swift 4.2

Button code in HTML side: HTML方面的按钮代码:

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

UIWebViewDelegate method: UIWebViewDelegate方法:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM