微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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];
}

原文地址:https://www.jb51.cc/js/153377.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐