背景:ios
UIWebView: iOS 用来展现 web 端内容的控件。git
1. 核心方法:github
- (NSString*)stringByEvaluatingJavaScriptFromString:(NSString *)script;
script 就是 JS 代码,返回结果为 js 执行结果。 好比一个 JS function 为web
function testFunction(abc){ return abc; };
webview 调用此 JS 代码以下:apache
NSString *js = @"testFunction('abc')"; NSString *result = [webView stringByEvaluatingJavaScriptFromString:js];
2. 重要回调:
网络
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
webview 每当须要去加载一个 request 就先回调这个方法,让上层决定是否 加载。通常在这里截获,进行本地的处理。app
Native 调用 JS:异步
本质就一个方法,经过 stringByEvaluatingJavaScriptFromString,都是同步。lua
下面重点说说JS怎么回调Native:url
1.一般方法:js修经过改doucument的loaction或者新建一个看不见的iFrame,修改它的 src,就会触发回调 webView 的 shouldStartLoadWithRequest,参数 request 的 url 就是新赋值的 location 或者 url,上层截获这个 url 的参数,对此分发便可。 这个都是异步调用的。
如 JS function:
var messagingIframe; messagingIframe = document.createElement('iframe'); messagingIframe.style.display = 'none'; document.documentElement.appendChild(messagingIframe);
function TestIOSJS(){ messagingIframe.src = "ios/test/click"; };
当触发上面的JS时,webview会收到下面的回调:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSString *url = request.URL.absoluteString; if([url hasSuffix:@"ios/test/click"]){ //do something you want return NO; } return YES; }
经过截获这个request的参数就能够作native须要作的事情。
有个开源的代码挺不错的,你们能够看看:https://github.com/marcuswestin/WebViewJavascriptBridge
2.经过XMLHttpRequest:
(1) Native子类化一个NSURLProtocol类,并经过[NSURLProtocol registerClass:self];把本身注册。
(2) JS function 建立一个 XMLHttpRequest 对象,而后能够设置携带的参数,设置同步或者异步,而后经过 send 发送请求。
function iOSExec(){ var execXhr = new XMLHttpRequest(); execXhr.open('HEAD', "/!test_exec?" + (+new Date()), true); //设置scheme var vcHeaderValue = /.*\((.*)\)/.exec(navigator.userAgent)[1]; execXhr.setRequestHeader('vc', vcHeaderValue);//设置参数等 execXhr.setRequestHeader('rc', 1); // 发起请求 execXhr.send(null); };
(3) 由于步骤1已经把本身注册,因此每一个客户端的网络请求都会请求这个类 的+(BOOL)canInitWithRequest:(NSURLRequest *)request,让此决定是否须要生成这个request。
@implementation TestURLProtocol +(void)initProtocol { [NSURLProtocol registerClass:self]; } +(BOOL)canInitWithRequest:(NSURLRequest *)request{ NSString *url = request.URL.absoluteString; if([url containsString:@"!test_exec"]){ //do something } return NO; }
(4) 经过获取这个request的参数,上层能够进行拦截,而后进行本地的相 关操做。
这个方法比较少用,不过能解决JS同步回调Native的方法。
这里也有一个开源库,你们能够看一下:https://github.com/apache/cordova-ios/tree/master/CordovaLib
The End.