I want to get the url of a tapped link in WKWebView
. The links are in a custom format that will trigger certain actions in the app. e.g. http://my-site/help#deeplink-intercom
. I am using KVO
like so:
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!!")
}
This works great when the link is tapped on the first time. However if I tap the same link twice in a row it won't report the link tap (obviously because the actual value hasn't changed). Is there a workaround to fix this so I can detect every tap and get the link? Any pointer on this would be great! Thanks!
You need to turn the string into a URL , then put the URL into an URLRequest , and WKWebView will load that. Fortunately it's not hard to do! Warning: Your URL must be complete, and valid, in order for this process to work. That means including the https:// part.
The culprit is HTML attribute target set to value _blank which is used to signal links that should be opened in new tab instead of the current one. This target setting is meant to tell the browser (which is WKWebView in this case) that this link should be open in new tab by default. Which is the root of the problem.
Open the Safari browser and navigate to any website. Once the website loads, click the “aA” icon available in the top corner positioned before the address bar. It opens the website view menu. From the available options, choose the “Request Desktop Website” option.
With func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { , you get the file url to download. Then download it with JS.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With