How UIWebView detect

2020-03-31 03:33发布

问题:

I know that method below can detect a link element tap. But I want to know if the UIView can detect if the img element is tapped?

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
switch (navigationType) {
    case UIWebViewNavigationTypeLinkClicked:
        NSLog(@"link is click");
        //do something
        break;
    default:
        break;
   }

    return true;
}

Some html source like below:

<p>xxxxxxxxx</p>
<p><img src="http://imgs.ebrun.com/resources/2015_06/2015_06_16/201506167911434413787546.jpg"> </p>
<p>xxxxxxxxx。</p>
<p><img src="http://imgs.ebrun.com/resources/2015_06/2015_06_16/201506167911434413787546.jpg"> </p>
<p>xxxxxxxxx。</p>

Could you show me how to do it using sample code? Thanks.

回答1:

Your img tag does not have html click event. If you can make your image like below way -

<p>xxxxxxxxx</p>
<p><img src="http://imgs.ebrun.com/resources/2015_06/2015_06_16/201506167911434413787546.jpg" onclick="myfunction()"> </p>
<p>xxxxxxxxx。</p>
<p><img src="http://imgs.ebrun.com/resources/2015_06/2015_06_16/201506167911434413787546.jpg" onclick="myfunction()"> </p>
<p>xxxxxxxxx。</p>

Then you can catch your img click event within UIWebView Delegate method - shouldStartLoadWithRequest.

Alternate possible option -

Otherwise you have write a javascript method which dynamically add OnClick method to all IMG tags. And call this javascript method when your page load in UIWebView -

- (void) webViewDidFinishLoad:(UIWebView *)webView
{
    //Execute javascript method or pure javascript if needed
    [_webView stringByEvaluatingJavaScriptFromString:@"methodName();"];
}


回答2:

Maybe this answer can help you. Basically you need to wrap tag inside tag and handle button click event inside

webView:shouldStartLoadWithRequest:navigationType

method