iOS web view 与 js 交互
移动应用中许多复杂的且经常改动的页面会使用H5进行代替native,这里就会使用到js和webview的交互
iOS里面,UIWebView提供了方法stringByEvaluatingJavaScriptFromString:使js和webview互通
这里我提供一种思路,仅供参考
1.加载js函数
var Test = {}; Test.platform = { name: 'IOS' }; // 返回App识别ID Test.getAppId = function(){ return '[AppId]'; }; // 返回用户Id Test.getUserId = function(){ return '[UserId]'; }; // 返回当前AppVersion Test.getAppVersion = function(){ return '[AppVersion]'; }; Test.open = function(str){ setTimeout(function(){ document.location = 'Test://open/'+str; },50); }; window.Test = Test;
2.简单几个函数,加载前替换掉自己的value,
for (NSString *key in dict) { NSString *placekey = [NSString stringWithFormat:@"[%@]", key]; NSString *value = [dict[key] stringValue]; if (! value || [value isEqual:[NSNull null]]) { jsString = [jsString stringByReplacingOccurrencesOfString:placekey withString:@"null"]; }else{ jsString = [jsString stringByReplacingOccurrencesOfString:placekey withString:value]; } }
3.加入webview的js里面:
[webView stringByEvaluatingJavaScriptFromString:jsString];
当js调用native的操作时候,可以使用Test.open(firstViewController?paramter=123)
native的delegate将会调用:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
这里的request.url将会是:
Test://open/firstViewController?paramter=123
进入我们自己解析方法,对此url进行不同的解析和跳转
NSString *requestString = [[request URL] absoluteString]; NSArray *components = [requestString componentsSeparatedByString:@"://"]; if (components[0] && [components count] > 1) {//如果协议抬头为Test或者为其他则走自定义流程 NSString *content = components[1]; NSArray *controller = [content componentsSeparatedByString:@"/"]; if (controller.count > 1 && [controller[0] isEqual:@"open"]) {//打开特定的controller [self openController:controller[1]]; } } return NO;