在 WKWebView 中获取 link URL

Getting the link URL tapped in WKWebView

我想在 WKWebView 中获取点击的 link 的 url。 links 采用自定义格式,将触发应用程序中的某些操作。例如http://my-site/help#deeplink-intercom。我像这样使用 KVO

override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.navigationDelegate = self
        webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
        view = webView
    }

 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if let newValue = change?[.newKey] {
            print("url changed: \(newValue)")
        }
        print("Did tap!!")
    }

第一次点击 link 时效果很好。但是,如果我连续点击相同的 link 两次,它不会报告 link 点击(显然是因为实际值没有改变)。是否有解决此问题的解决方法,以便我可以检测到每次点击并获得 link?关于此的任何指示都很棒!谢谢!

像这样改变addObserver

webView.addObserver(self, forKeyPath: "URL", options: [.new, .old], context: nil)

observeValue函数中你可以获得两个值

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])
    }else{
        //Value not Changed
        print(change?[.oldKey])
    }
}

您可以使用WKWebView 委托方法。并且不要忘记将 webview 委托设置为 self:webview.navigationDelegate = self

func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: ((WKNavigationActionPolicy) -> Void)) {

    switch navigationAction.navigationType {
        case .LinkActivated:
        if navigationAction.targetFrame == nil {
            self.webView?.loadRequest(navigationAction.request)// It will load that link in same WKWebView
        }
        default:
            break
    }

    if let url = navigationAction.request.URL {
        print(url.absoluteString) // It will give the selected link URL

    }
    decisionHandler(.Allow)
}

Swift 5.0

记得在 WKWebView 实例上设置 navigationDelegate。

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    print(String(describing: navigationAction))
    decisionHandler(.allow)
}