Intercept request with WKWebView

前端 未结 6 602
遇见更好的自我
遇见更好的自我 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:28

    there are many ways to implement intercepter request.

    1. setup a local proxy, use WKNavigationDelegate

      -[ViewController webView:decidePolicyForNavigationAction:decisionHandler:]
      

      load new request and forward to local server, and at the local server side you can do something(eg. cache).

    2. private api. use WKBrowsingContextController and custom URLProtocol

      Class cls = NSClassFromString(@"WKBrowsingContextController");
      SEL sel = NSSelectorFromString(@"registerSchemeForCustomProtocol:");
      if ([(id)cls respondsToSelector:sel]) {
          // 把 http 和 https 请求交给 NSURLProtocol 处理
          [(id)cls performSelector:sel withObject:@"http"];
          [(id)cls performSelector:sel withObject:@"https"];
      }
      
    3. use KVO to get system http/https handler.(ios 11, *)

      WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
      URLSchemeHandler *schemeHandler = [[URLSchemeHandler alloc] init];
      [configuration setURLSchemeHandler:schemeHandler forURLScheme:@"test"];
      NSMutableDictionary *handlers = [configuration valueForKey:@"_urlSchemeHandlers"];
      handlers[@"http"] = schemeHandler;
      handlers[@"https"] = schemeHandler;
      

      all the three ways you probably need handle CORS & post bodies to be stripped,you overwrite change browser`s option request( Preflighted_requests),you can custom http header to replace http body for post bodies to be stripped.

提交回复
热议问题