简体   繁体   中英

iOS WKWebview how to detect when I click on an image inside of <a> tag

I'm trying to change my UIWebView to WKWebView in my app ( Objective-C ). I see WKWebView contain tag "a" and inside of tag "a" contain tag "image":

<a href="http://click.adzcore.com/xyz"><img src="http://www.abc.xyz/smart/images/bnr/yyy.png" width="320" height="50" border="0" alt="+alt[n]+" onclick="_gaq.push(['_trackPageview','/smart/count/frognote']);"></a>

I want detect when user click on image, so I do:

- (void)webView:(WKWebView )webView decidePolicyForNavigationAction:(WKNavigationAction )navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {

    if (navigationAction.navigationType == WKNavigationTypeLinkActivated) {
        NSURL *url = navigationAction.request.URL;
        [[UIApplication sharedApplication] openURL:url];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

But this code is not correct because WKNavigationTypeLinkActivated is not catched when user click on image.

After research I found a solution to solve my problem. I don't use WKNavigationTypeLinkActivated to catch event click on image.

My solution:

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {

    if ([navigationAction.request.URL.relativeString hasPrefix:@"http://click.adzcore.com/"]) {
        NSURL *url = navigationAction.request.URL;
        [[UIApplication sharedApplication] openURL:url];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }

    decisionHandler(WKNavigationActionPolicyAllow);
}

It's OK for my task :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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