javascript – 如何监视WKWebview上的请求?

如何监视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];
}

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...