链接点击监听器上的WKWebView?

时间:2017-09-16 12:42:55

标签: ios iphone swift swift3 wkwebview

WKWebView类中是否存在类似onLinkClickListener的内容?我试着谷歌搜索但没有发现任何东西,我也发现了一些关于simillar类型的stackoverflow的未解答的问题。

我需要linkClickListener的原因是,当我点击链接并且页面尚未加载时,它不会加载网站。当页面加载了监听器时,我也可以创建一个花哨的加载屏幕。

2 个答案:

答案 0 :(得分:25)

你可以这样做

将WKNavigationDelegate添加到您的班级

class ViewController: UIViewController, WKNavigationDelegate

设置导航委托

yourWKWebview.navigationDelegate = self

之后,您将能够使用decisionPolicyFor navigationAction函数

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

答案 1 :(得分:1)

这是您正在寻找的解决方案

来自 Bala 的原始回答:https://stackoverflow.com/a/44408807/8661382

为您的班级创建 WkNavigationDelegate

class ViewController: UIViewController, WKNavigationDelegate {
    }

覆盖方法 loadView 并添加一个 observer,如下所示:

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

viewDidLoad 中向您的 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
    }

最后,最重要的是像这样覆盖 observerValue 方法:

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

这将在加载链接之前打印您在 webView 上单击的链接。