检测何时在WKWebView中单击链接 [英] Detect when a link is clicked in a WKWebView

查看:175
本文介绍了检测何时在WKWebView中单击链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检测WKWebView中单击链接的时间?我正在UIWebView中寻找与之等效的东西.

How do you detect when a link was clicked in a WKWebView? I'm looking for the equivalent of this in a UIWebView.

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if(navigationType == UIWebViewNavigationTypeLinkClicked)
    {

    }
    return YES;
}

我在WKNavigationDelegate中尝试过此操作,但即使单击链接,也只能获得所有请求的WKNavigationTypeOther.

I tried this in the WKNavigationDelegate but I only ever get WKNavigationTypeOther for all requests even when clicking on links.

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    if(navigationAction.navigationType == WKNavigationTypeLinkActivated)
    {

    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

推荐答案

WkWebView中可以执行的操作如下:

What you can do in a WkWebView is the following:

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的属性并做出相应的响应.

In this delegate method, you get the URL request that the WKWebView is trying to open. There you can check the attributes of the URLRequest and respond accordingly.

您甚至可以为URLRequest编写扩展来处理该逻辑,以便您可以重用它.

You can even write an extension for URLRequest that handles that logic, so you can reuse it.

extension URLRequest {
    var isHttpLink: Bool {
        return self.url?.scheme?.contains("http") ?? false
    }
}

然后您可以将委托方法中的long条件更改为:

Then you can change the long condition in the delegate method to:

 // WKWebViewNavigationDelegate
 func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
   guard navigationAction.request.isHttpLink else {
        decisionHandler(.allow)
        return
    }
   // ... handle url

这篇关于检测何时在WKWebView中单击链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆