iOS web view 與 js 互動

來源:互聯網
上載者:User

標籤:

行動裝置 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 互動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.