How to handle link clicked in WKWebView in iOS

Issue #365

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import WebKit
import SafariServices

final class WebViewHandler: NSObject, WKNavigationDelegate {
var show: ((UIViewController) -> Void)?
let supportedSchemes = ["http", "https"]

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

guard
navigationAction.navigationType == .linkActivated,
let url = navigationAction.request.url,
let scheme = url.scheme,
supportedSchemes.contains(scheme)
else {
return
}

let controller = SFSafariViewController(url: url)
show?(controller)
}
}

Comments