標籤:
行動裝置 App中許多複雜的且經常改動的頁面會使用H5進行代替native,這裡就會使用到js和webview的互動
iOS裡面,UIWebView提供了方法stringByEvaluatingJavaScriptFromString:使js和webview互連
這裡我提供一種思路,僅供參考
1.載入js函數
var Test = {};Test.platform = {name: ‘IOS‘};// 返回App識別IDTest.getAppId = function(){ return ‘[AppId]‘;};// 返回使用者IdTest.getUserId = function(){ return ‘[UserId]‘;};// 返回當前AppVersionTest.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;
iOS web view 與 js 互動