Getting the link URL tapped in WKWebView
You can use WKWebView delegate method. And don't forget to set the webview delegate to 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)
}
Change addObserver
like this
webView.addObserver(self, forKeyPath: "URL", options: [.new, .old], context: nil)
In observeValue
function you able get both value
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])
}
}
Swift 5.0
Remember to set navigationDelegate on the WKWebView instance.
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
print(String(describing: navigationAction))
decisionHandler(.allow)
}