WKWebview捕获AJAX

2018-05-22  本文已影响777人  wwwwwwdi

项目中需求,要在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

上一篇 下一篇

猜你喜欢

热点阅读