Search code examples
iosswiftwkwebviewswift5

Tracking navigation in WKWebView doesn't work for button click


I am trying to catch a button click in my web view. Button "action" if I can say so, triggers certain url... I am not really able to catch this moment through WKNavigationDelegate. webview is set like this:

 lazy var advertWebKitView: WKWebView = {
        let webConfiguration = WKWebViewConfiguration()
        let preferences = WKPreferences()
        preferences.javaScriptEnabled = true
        webConfiguration.preferences = preferences
        let webView = WKWebView(frame: .zero, configuration: webConfiguration)

        webView.navigationDelegate = self
        webView.uiDelegate = self
        webView.translatesAutoresizingMaskIntoConstraints = false
        return webView
    }()

I am trying to catch that button click like this:

 func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        decisionHandler(.allow)
        guard let urlAsString = navigationAction.request.url?.absoluteString.lowercased() else {
            return
        }
        
        if urlAsString.range(of: "...") != nil {
           
        }
    }

but this method doesn't trigger when button is clicked.

On android, it works and its done like this:

@Override
        public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
            if (url.equals("...")) {
                finish();
            }
             //...
            super.doUpdateVisitedHistory(view, url, isReload);
        }

what would be equal method and a way to track navigation correctly through wkwebview?

EDIT: if there is some info needed about the webpage structure or so, please ask for details and I will add that too. I just didn't know which info may be relevant or helpful.

The button html looks like this:

<a class="lc-button lc-button--light" href="/close">OK</a>

Also one interesting thing is, that I have tried to use my code on other sites and navigation delegate methods were triggered correctly. Which leads me that problem is with our site and its html code or something about how the page is loaded after button is clicked, maybe...


Solution

  • Use RedirectTo instead of LinkTo in react router for redirecting to /close