Xcode, Swift; Detect hyperlink click in UIWebView

前端 未结 3 1189
予麋鹿
予麋鹿 2021-01-13 06:57

I made an iOS app with Xcode and Swift.

I want to open specific hyperlinks in Safari browser, there others in the WebView itself.

To reach this, I\'ll have t

相关标签:
3条回答
  • 2021-01-13 07:04

    please try

    for swift 3.0

     public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool
            {
             if navigationType == .linkClicked
             {
    
                }
                return true;
            }
    

    swift 2.2

    internal func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
        {
            if navigationType == .LinkClicked
            {
    
            }
            return true;
        }
    
    0 讨论(0)
  • 2021-01-13 07:07

    This is the working solution (Xcode 7.3.1 and Swift 2.2):

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    
        if request.URL?.query?.rangeOfString("target=external") != nil {
            if let url = request.URL {
                UIApplication.sharedApplication().openURL(url)
                return false
            }
        }
        return true
    }
    

    Many thanks to danhhgl from freelancer.com!

    0 讨论(0)
  • 2021-01-13 07:18

    I think you can solve with this code:

     function reportBackToObjectiveC(string)
     {
     var iframe = document.createElement("iframe");
     iframe.setAttribute("src", "callback://" + string);
     document.documentElement.appendChild(iframe);
     iframe.parentNode.removeChild(iframe);
     iframe = null;
     }
    
    var links = document.getElementsByTagName("a");
    for (var i=0; i<links.length; i++) {
    links[i].addEventListener("click", function() {
        reportBackToObjectiveC("link-clicked");
    }, true);
    }
    

    in ios code:

    if ([[[request URL] scheme] isEqualToString:@"callback"]) {
    [self setNavigationLeavingCurrentPage:YES];
    return NO;
    }
    

    More details you can check from here:

    0 讨论(0)
提交回复
热议问题