msung
msung

Reputation: 3742

Stop WKWebView from opening link in external app

I have an almost completely empty app consisting mainly of an WKWebView.

The usecase is basically a browser.

When clicking a link to a domain, that has an own app linked to the domain and whose app (linked via apple-app-site-association) is installed on the device, how can I stop the link being opened by the app (instead of my webview)?

I tried implementing methods of WKNavigationDelegate but was only able to cancel the navigation altogether.

What I want to happen:

  1. my app is started
  2. a website is loaded into my webview
  3. user clicks on link to https://foo.bar.com/some/path
  4. the page https://foo.bar.com/some/path is opened in my webview

What happens instead:

  1. my app is started
  2. a website is loaded into my webview
  3. user clicks on link to https://foo.bar.com/some/path
  4. the app of foo.com.bar is opened instead the website inside my webview

Upvotes: 1

Views: 931

Answers (1)

Andres Paladines
Andres Paladines

Reputation: 1218

If the goal is to open any link in the same page, you can try the next implementation:

It worked for me (by the time I implemented it). Hopefully will work for you.

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {

    var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
    
        webView = WKWebView(frame: view.bounds)
        webView.navigationDelegate = self
        view.addSubview(webView)
    
        if let url = URL(string: "https://www.example.com") {
            webView.load(URLRequest(url: url))
        }
    }

    // MARK: WKNavigationDelegate

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,
                     decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if navigationAction.targetFrame == nil || navigationAction.targetFrame?.isMainFrame == false {
            // If the navigation action does not have a target frame or it is not the main frame,
            // load the request in the same view by calling `load(_:)` on the WKWebView instance.
            webView.load(navigationAction.request)
            decisionHandler(.cancel)
        } else {
            // If the navigation action has a target frame and it is the main frame, allow the navigation to proceed.
        decisionHandler(.allow)
        }
    }
}

Upvotes: 0

Related Questions