WKWebView on link click listener?

You can do it like this

add WKNavigationDelegate to your class

class ViewController: UIViewController, WKNavigationDelegate

set a navigation delegate

yourWKWebview.navigationDelegate = self

after that you will be able to use decidePolicyFor navigationAction function

 func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if navigationAction.navigationType == WKNavigationType.linkActivated {
            print("link")

            decisionHandler(WKNavigationActionPolicy.cancel)
            return
        }
        print("no link")
        decisionHandler(WKNavigationActionPolicy.allow)
 }

Here is the solution you were looking for

Original answer from Bala: https://stackoverflow.com/a/44408807/8661382

Create WkNavigationDelegate to your class:

class ViewController: UIViewController, WKNavigationDelegate {
    }

Override the method loadView and add an observer like this:

override func loadView() {
        webView = WKWebView()
        webView.navigationDelegate = self
        webView.addObserver(self, forKeyPath: "URL", options: [.new, .old], context: nil)
        view = webView
    }

In viewDidLoad add an url to your webView.:

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController?.setNavigationBarHidden(false, animated: true)
    
    let url = URL(string: "https://www.hackingwithswift.com")!
    webView.load(URLRequest(url: url))
    webView.allowsBackForwardNavigationGestures = true
    }

Finally, most importantly override observerValue method like this:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, 
    change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if let newValue = change?[.newKey] as? Int, let oldValue = change? 
    [.oldKey] as? Int, newValue != oldValue {
        //Value Changed
        print(change?[.newKey] as Any)
    }else{
        //Value not Changed
        print(change?[.oldKey] as Any)
    }
    }

This will print the link you click on webView before loading the link.