如何检测WKWebView中单击链接的时间?我在UIWebView中寻找相同的东西。
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
if(navigationType == UIWebViewNavigationTypeLinkClicked)
{
}
return YES;
}
我在WKNavigationDelegate
中尝试了此操作,但即使点击链接,我也只能获得WKNavigationTypeOther
所有请求。
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
if(navigationAction.navigationType == WKNavigationTypeLinkActivated)
{
}
decisionHandler(WKNavigationActionPolicyAllow);
}
答案 0 :(得分:4)
您可以在WkWebView
中进行以下操作:
override func viewDidLoad() {
super.viewDidLoad()
let webView = WKWebView()
self.view.addSubview(webView) // you need to also setup constraints here - I left out for clarity
// Make sure you set the delegate, so you get the callback
self.webView.navigationDelegate = self
}
// WKWebViewNavigationDelegate
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.url, let scheme = url.scheme, scheme.contains("http") else {
// This is not HTTP link - can be a local file or a mailto
decisionHandler(.cancel)
return
}
// This is a HTTP link
open(url: url)
decisionHandler(.allow)
}
在此委托方法中,您获得WKWebView
试图打开的URL请求。在那里,您可以检查URLRequest
的属性并做出相应的响应。
您甚至可以为URLRequest
写一个扩展程序来处理该逻辑,以便您可以重用它。
extension URLRequest {
var isHttpLink: Bool {
return self.url?.scheme?.contains("http") ?? false
}
}
然后您可以将委托方法中的long条件更改为:
// WKWebViewNavigationDelegate
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard navigationAction.request.isHttpLink else {
decisionHandler(.allow)
return
}
// ... handle url