针对的是UIWebView
如果不使用 UIWebView 此库已经过时了。但是思想值得学习。
思路
1、注入一个全局对象 EasyJS。
__callbacks 负责以 callbackid 为key 存储 回调函数。
invokeCallback 负责根据OC端回传的 callbackid 从 __callbacks 拿出 回调函数 并调用
call 负责拼接 iframe的src 调用起OC端代理方法 在代理方法中解析 类名 方法名 参数 以及回调 callbackid
inject 负责以生成 {obj:{jsMethod:function (){
return EasyJS.call(obj, method, Array.prototype.slice.call(arguments));
},...}} ,并加入到全局window中。
JS端 代码解析
inject: function (obj, methods){
window[obj] = {};
var jsObj = window[obj];
for (var i = 0, l = methods.length; i < l; i++){
(function (){
var method = methods[i];
var jsMethod = method.replace(new RegExp(":", "g"), "");
// 此处将匿名函数 作为键值对保存 类似于block
// 应该注意到 arguments 是变化的 在具体的调用时才确定个数和参数类型 类似于OC的可变参数方法
jsObj[jsMethod] = function (){
return EasyJS.call(obj, method, Array.prototype.slice.call(arguments));
};
})();
}
}
//例如 arguments 只有一个 而且是函数类型
MyJSTest.testWithFuncParam(function (data){
alert(data); //data would be blabla:"bla
return "some data";
});
//所以当调用时
call: function (obj, functionName, args){
var formattedArgs = [];
for (var i = 0, l = args.length; i < l; i++){
//根据args[i] 类型来判断是否有回调函数
if (typeof args[i] == "function"){
formattedArgs.push("f");
var cbID = "__cb" + (+new Date);
// 类似于 WebViewJavascriptBridge 生成唯一callbackid 和全局字典保存回调函数 并将 callbackid 通过代理传递给OC
EasyJS.__callbacks[cbID] = args[i];
formattedArgs.push(cbID);
}else{
formattedArgs.push("s");
formattedArgs.push(encodeURIComponent(args[i]));
}
}
var argStr = (formattedArgs.length > 0 ? ":" + encodeURIComponent(formattedArgs.join(":")) : "");
var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", "easy-js:" + obj + ":" + encodeURIComponent(functionName) + argStr);
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
// 不理解的是 获取返回值的时候 不用考虑时机 一定能获取到?如果调用的OC方法很耗时 呢?
var ret = EasyJS.retValue;
EasyJS.retValue = undefined;
if (ret){
return decodeURIComponent(ret);
}
}
//最后是处理回调
invokeCallback: function (cbID, removeAfterExecute){
var args = Array.prototype.slice.call(arguments);
// 这两步是 因为前两个参数是不需要的 丢弃
args.shift();
args.shift();
for (var i = 0, l = args.length; i < l; i++){
args[i] = decodeURIComponent(args[i]);
}
//根据回传的callbackid 取出调用call时存储的回调函数
// 执行
var cb = EasyJS.__callbacks[cbID];
if (removeAfterExecute){
EasyJS.__callbacks[cbID] = undefined;
}
return cb.apply(null, args);
},
OC端 代码解析
核心方法
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSString *requestString = [[request URL] absoluteString];
if ([requestString hasPrefix:@"easy-js:"]) {
/*
A sample URL structure:
easy-js:MyJSTest:test
easy-js:MyJSTest:testWithParam%3A:haha
*/
NSArray *components = [requestString componentsSeparatedByString:@":"];
//NSLog(@"req: %@", requestString);
//利用动态运行时 构建 NSInvocation 执行方法
NSString* obj = (NSString*)[components objectAtIndex:1];
NSString* method = [(NSString*)[components objectAtIndex:2]
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSObject* interface = [javascriptInterfaces objectForKey:obj];
// execute the interfacing method
SEL selector = NSSelectorFromString(method);
NSMethodSignature* sig = [[interface class] instanceMethodSignatureForSelector:selector];
NSInvocation* invoker = [NSInvocation invocationWithMethodSignature:sig];
invoker.selector = selector;
invoker.target = interface;
NSMutableArray* args = [[NSMutableArray alloc] init];
// 判断是否有参数传递
if ([components count] > 3){
NSString *argsAsString = [(NSString*)[components objectAtIndex:3]
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSArray* formattedArgs = [argsAsString componentsSeparatedByString:@":"];
for (int i = 0, j = 0, l = [formattedArgs count]; i < l; i+=2, j++){
NSString* type = ((NSString*) [formattedArgs objectAtIndex:i]);
NSString* argStr = ((NSString*) [formattedArgs objectAtIndex:i + 1]);
// 是否有回调函数
if ([@"f" isEqualToString:type]){
// 有回调函数 则构建 EasyJSDataFunction 实例 ,传参给具体的调用函数 此实例会调用 executeWithParams 来实现回调
EasyJSDataFunction* func = [[EasyJSDataFunction alloc] initWithWebView:(EasyJSWebView *)webView];
func.funcID = argStr;//回调的callbackid
[args addObject:func];
[invoker setArgument:&func atIndex:(j + 2)];
}else if ([@"s" isEqualToString:type]){
NSString* arg = [argStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[args addObject:arg];
[invoker setArgument:&arg atIndex:(j + 2)];
}
}
}
[invoker invoke];
//return the value by using javascript
if ([sig methodReturnLength] > 0){
// 执行这段代码的时机 和 一定 比js拿取返回值的时机延后吗???
NSString* retValue;
[invoker getReturnValue:&retValue];
if (retValue == NULL || retValue == nil){
[webView stringByEvaluatingJavaScriptFromString:@"EasyJS.retValue=null;"];
}else{
retValue = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef) retValue, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8));
[webView stringByEvaluatingJavaScriptFromString:[@"" stringByAppendingFormat:@"EasyJS.retValue=\"%@\";", retValue]];
}
}
[args release];
return NO;
}
if (! self.realDelegate){
return YES;
}
return [self.realDelegate webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
}
//EasyJSDataFunction 类 核心方法 直接调用js 回传callbackid 和参数
- (NSString*) executeWithParams: (NSArray*) params{
NSMutableString* injection = [[NSMutableString alloc] init];
[injection appendFormat:@"EasyJS.invokeCallback(\"%@\", %@", self.funcID, self.removeAfterExecute ? @"true" : @"false"];
// 拼接回调的参数 如果有的话
if (params){
for (int i = 0, l = params.count; i < l; i++){
NSString* arg = [params objectAtIndex:i];
NSString* encodedArg = (NSString*) CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)arg, NULL, (CFStringRef) @"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8);
[injection appendFormat:@", \"%@\"", encodedArg];
}
}
[injection appendString:@");"];
if (self.webView){
return [self.webView stringByEvaluatingJavaScriptFromString:injection];
}else{
return nil;
}
}
// 注入 js 核心代码
- (void)webViewDidStartLoad:(UIWebView *)webView{
[self.realDelegate webViewDidStartLoad:webView];
if (! self.javascriptInterfaces){
self.javascriptInterfaces = [[NSMutableDictionary alloc] init];
}
NSMutableString* injection = [[NSMutableString alloc] init];
//inject the javascript interface
// 利用动态运行时 获取类全部的方法
for(id key in self.javascriptInterfaces) {
NSObject* interface = [self.javascriptInterfaces objectForKey:key];
[injection appendString:@"EasyJS.inject(\""];
[injection appendString:key];
[injection appendString:@"\", ["];
unsigned int mc = 0;
Class cls = object_getClass(interface);
Method * mlist = class_copyMethodList(cls, &mc);
for (int i = 0; i < mc; i++){
[injection appendString:@"\""];
[injection appendString:[NSString stringWithUTF8String:sel_getName(method_getName(mlist[i]))]];
[injection appendString:@"\""];
if (i != mc - 1){
[injection appendString:@", "];
}
}
free(mlist);
[injection appendString:@"]);"];
}
NSString* js = INJECT_JS;
//inject the basic functions first
[webView stringByEvaluatingJavaScriptFromString:js];
//inject the function interface
[webView stringByEvaluatingJavaScriptFromString:injection];
[injection release];
}