Intercept request with WKWebView

前端 未结 6 594
遇见更好的自我
遇见更好的自我 2021-02-04 05:32

Now i\'m using UIWebView and with canInitWithRequest: of NSURLProtocol i can intercept all requests and do with it what I want.

In

6条回答
  •  一生所求
    2021-02-04 06:24

    You can intercept requests on WKWebView since iOS 8.0 by implementing the decidePolicyFor: navigationAction: method for the WKNavigationDelegate

     func webView(_ webView: WKWebView, decidePolicyFor 
           navigationAction: WKNavigationAction, 
           decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void) {
    
        //link to intercept www.example.com
    
        // navigation types: linkActivated, formSubmitted, 
        //                   backForward, reload, formResubmitted, other
    
        if navigationAction.navigationType == .linkActivated {
            if navigationAction.request.url!.absoluteString == "http://www.example.com" {
                //do stuff
    
                //this tells the webview to cancel the request
                decisionHandler(.cancel)
                return
            }
        }
    
        //this tells the webview to allow the request
        decisionHandler(.allow)
    
    }
    

提交回复
热议问题