如何监视WKWebview的请求?
我尝试使用NSURLprotocol(canInitWithRequest),但它不会监视ajax请求(XHR),只有导航请求(文档请求)
解决方法
最后我解决了
由于我无法控制Web视图内容,所以我向WKWebview注入了一个包含jQuery AJAX请求监听器的java脚本.
当监听器捕获请求时,它会在方法中发送本机应用程序请求主体:
webkit.messageHandlers.callbackHandler.postMessage(data);
本机应用程序在委托中捕获消息:
(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
并执行相应的动作
这里是相关代码:
ajaxHandler.js –
//Every time an Ajax call is being invoked the listener will recognize it and will call the native app with the request details $( document ).ajaxSend(function( event,request,settings ) { callNativeApp (settings.data); }); function callNativeApp (data) { try { webkit.messageHandlers.callbackHandler.postMessage(data); } catch(err) { console.log('The native context does not exist yet'); } }
我的ViewController代理是:
@interface BrowserViewController : UIViewController <UIWebViewDelegate,WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler,UIWebViewDelegate>
在我看来,DidLoad我正在创建一个Wkwebview:
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc]init]; [self addUserScriptToUserContentController:configuration.userContentController]; appWebView = [[WKWebView alloc]initWithFrame:self.view.frame configuration:configuration]; appWebView.UIDelegate =self; appWebView.navigationDelegate=self; [appWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString: @"http://#############"]]];
这是addUserScriptToUserContentController:
- (void) addUserScriptToUserContentController:(WKUserContentController *) userContentController{ NSString *jsHandler = [NSString stringWithContentsOfURL:[[NSBundle mainBundle]URLForResource:@"ajaxHandler" withExtension:@"js"] encoding:NSUTF8StringEncoding error:NULL]; WKUserScript *ajaxHandler = [[WKUserScript alloc]initWithSource:jsHandler injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO]; [userContentController addScriptMessageHandler:self name:@"callbackHandler"]; [userContentController addUserScript:ajaxHandler]; }