Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WKWebView on link click listener?

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.

like image 624
Samuel Kodytek Avatar asked Sep 16 '17 12:09

Samuel Kodytek


2 Answers

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)
 }
like image 87
Vitaly Migunov Avatar answered Nov 11 '22 04:11

Vitaly Migunov


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.

like image 44
Fazle Rabbi Linkon Avatar answered Nov 11 '22 06:11

Fazle Rabbi Linkon