WKWebview捕获AJAX

项目中需求,要在webview的页面中插入JS语句
今天获取到一个BUG,webview加载url之后,并不能成功执行语句
经过一番排查之后,发现是webview网页中存在使用AJAX技术,而AJAX在WKWebview的代理方法中并不能捕获到

方法1

因此:

查阅了一些资料之后,得出以下结论:
先贴上参考资料

先说想法:

因为我们是要监听js层面的AJAX回调,
而在iOS层面的webview中,无法监听这个事件,
所以我们需要在webview执行的时候,植入js相关的脚本,
然后在JS层面获取到回调之后,
使用JS与OC交互,传给iOS层
  1. 首先创建webview
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://#############"]]];   

  1. 遵循代理
@interface SQWebViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>
  1. 植入脚本方法
///植入脚本
- (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];
}
  1. 脚本文件
//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');
    }
}
  1. 回调方法,在WKScriptMessageHandler代理中有一个方法
/*! @abstract Invoked when a script message is received from a webpage.
 @param userContentController The user content controller invoking the
 delegate method.
 @param message The script message received.
 */
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message;

但是:

要核实js层使用的AJAX方法名是否匹配?

方法二:

我们还可以使用第三方库
WebViewJavascriptBridge
具体使用方法,详见README

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容