Home > Enterprise >  how do I perform tasks before loading a webview url in ios?
how do I perform tasks before loading a webview url in ios?

Time:08-04

so I can't seem to figure out a way to perform some tasks before loading a url in ios webview. Like in android we can use shouldOverrideUrlLoading.

@Override
public boolean shouldOverrideUrlLoading(final WebView view, String url) {
   ///sometask
}

but I can't find a function that does something like this in ios. Say a user clicked on a href tag inside the webview that takes it to different page, how do I know what link that tag takes the user to? before changing the page.

Basically I want to check what url the webpage is about to load and perform extra steps according to that url.

CodePudding user response:

You can use WKNavigationDelegate

set navigationDelegate in viewDidLoad

self.webView?.navigationDelegate = self

Observe URL in below navigationDelegate Method.

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
        
        DispatchQueue.main.async {
            if let urlString = navigationAction.request.url?.absoluteString{
                  
                  print(urlString)
             }
         }

    decisionHandler(.allow)
}
  • Related