0

I wrote a simple app which calls a webview (located at XXXXXX.com/webview.php

This is my code which opens my webview in swift:

if let url = URL(string: "https://www.XXXXXX.com/webview.php") {
    let request = URLRequest(url: url)
    webView.loadRequest(request)
}

Now, all internal links which are within this webview-system (e.g. /webview_subsite2.php) are opening within this webview. Thats wonderful. BUT I want that all external links (target=_blank) open in Safari-Browser. How can I achieve this?

My previous question was marked as duplicate, but it isnt. The point is, that the above posted code is NOT the call of a link! It is the call of the webview. My question concerns how to open all external links INSIDE this webview, which is located at XXXXXX.com/webview.php (domain censored) in Safari and NOT within this webview-Frame. And a solution in swift is necessary.

newcoder
  • 21
  • 1
  • 4

2 Answers2

0

use shouldStartLoadWithRequest webView delegate method and check navigationType.linkClicked type and open the link in safari

func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    if navigationType == UIWebViewNavigationType.linkClicked {
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(request.url!, options: [:])
        } else {
            UIApplication.shared.openURL(url)
        }
        return false
    }
    return true
}
Suhit Patil
  • 11,748
  • 3
  • 50
  • 60
0

You can implement webView:decidePolicyForNavigationAction:decisionHandler: on your WKNavigationDelegate. Return WKNavigationActionPolicyAllow to the completion handler for URLs that match your "internal" domain, and WKNavigationActionPolicyCancel for ones that don't, and also handle those URLs to load in Safari.

greymouser
  • 3,133
  • 19
  • 22