WKWebView on link click listener?

Samuel Kodytek picture Samuel Kodytek · Sep 16, 2017 · Viewed 15.4k times · Source

Does there exist something like a onLinkClickListener in the WKWebView class? I tried googling it but found nothing, I also found some unanswered questions on stackoverflow of simillar type.

The reason I need a linkClickListener is that, when I click on a link and the page did not load yet, it does not load the website. I also could create a fancy loading screen, when the page is loading with the listener.

Answer

Vitaly Migunov picture Vitaly Migunov · Sep 16, 2017

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)
 }