以前NSURLProtocol可以直接拦截UIWebView,后面升级成WKWebView发现拦截不到了
有细心爱研究的老铁发现了 [WKBrowsingContextController registerSchemeForCustomProtocol:] 这个函数的存在
所以还是可以拦截的
直接上步骤
1.在控制器或者你喜欢的地方注册NSURLProtocol(调用以下代码)
-
- Class cls = NSClassFromString(@"WKBrowsingContextController");
-
- SEL sel = NSSelectorFromString(@"registerSchemeForCustomProtocol:");
- if ([(id)cls respondsToSelector:sel]) {
-
- [(id)cls performSelector:sel withObject:@"http"];
-
- [(id)cls performSelector:sel withObject:@"https"];
- }
- [NSURLProtocol registerClass:[CustomProtocol class]];
2.在你自定义的NSURLProtocol类中实现拦截
- + (BOOL)canInitWithRequest:(NSURLRequest *)request{
-
- NSString *abstring = request.URL.absoluteString;
-
- if ([abstring containsString:@"你喜欢的标记"]) {
- return YES;
- }
-
- return NO;
- }
-
- + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
- {
- return request;
- }
3.在你自定义的NSURLProtocol类中拦截后替换请求的内容,以下以图片为例
- - (void)startLoading{
-
- NSString *urlPathString = super.request.URL.absoluteString;
-
- if ([urlPathString containsString:@"你喜欢的标记"]) {
-
- urlPathString = [urlPathString stringByReplacingOccurrencesOfString:@"你喜欢的标记" withString:@"你喜欢的标记2"];
- }
-
-
- NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlPathString]];
-
- NSMutableDictionary *header = [NSMutableDictionary dictionary];
-
- header[@"Content-Length"] = [NSString stringWithFormat:@"%ld",imageData.length];
-
- NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:self.request.URL
- statusCode:200 HTTPVersion:@"1.1" headerFields:header];
- //回调
- [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed];
- [self.client URLProtocol:self didLoadData:imageData];
- [self.client URLProtocolDidFinishLoading:self];
-
- }
-
- - (void)stopLoading{
- NSLog(@"stop");
- }