UIWebView與JavaScript的那些事兒

來源:互聯網
上載者:User

UIWebView是IOS SDK中渲染網面的控制項,在顯示網頁的時候,我們可以hack網頁然後顯示想顯示的內容。其中就要用到javascript的知識,而UIWebView與javascript互動的方法就是stringByEvaluatingJavaScriptFromString:

有了這個方法我們可以通過objc調用javascript,可以注入javascript。

首先我們來看一下,如何調用javascript:

[webView stringByEvaluatingJavaScriptFromString:@"myFunction();"];

這兒myFunction()就是我們的javascript方法。

再來看看入何注入javascript,我們先寫一個需要注入的javascript:

function showAlert() {alert('in show alert');}

儲存為test.js,然後拖到xcode 的resource分組下。再用代碼在初始化的時候注入這個js(如在viewDidLoad方法裡)。

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"js"];NSString *jsString = [[NSString alloc] initWithContentsOfFile:filePath];[webView stringByEvaluatingJavaScriptFromString:jsString];

這樣就注入了上面的js,那麼我們可以隨時調用js的方法,如何調用,上面有介紹。


那麼我們能不能通過js來調用objc的方法呢。 當然可以,原理就是利用UIWebView重新導向請求,傳一些命令到我們的UIWebView,在UIWebView的delegate的方法中接收這些命令,並根據命令執行相應的objc方法。這樣就相當於在javascript中調用objc的方法。說起來有點抽象,看看代碼一下就明白。

首先我們寫一個javascript 方法如下:

function sendCommand(cmd,param){var url="testapp:"+cmd+":"+param;document.location = url;}function clickLink(){sendCommand("alert","你好嗎?");}

然後在你的html裡調用這個js方法 如:

<input type="button" value="Click me!" onclick="clickLink()" /><br/>

最後我們在UIWebVew中截獲這個重新導向請求:

#pragma mark --#pragma mark UIWebViewDelegate- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {NSString *requestString = [[request URL] absoluteString];NSArray *components = [requestString componentsSeparatedByString:@":"];if ([components count] > 1 && [(NSString *)[components objectAtIndex:0] isEqualToString:@"testapp"]) {if([(NSString *)[components objectAtIndex:1] isEqualToString:@"alert"]) {UIAlertView *alert = [[UIAlertView alloc]   initWithTitle:@"Alert from Cocoa Touch" message:[components objectAtIndex:2]  delegate:self cancelButtonTitle:nil  otherButtonTitles:@"OK", nil];[alert show];}return NO;}return YES;}

看了代碼是不是清楚得不能再清楚了呀?  我想phonegap可能與是這樣實現的,沒去研究過。 不過有一個開源工程大家可以看看,它允許javascript調用objective_c的方法。叫jsbridge-to-cocoa

http://code.google.com/p/jsbridge-to-cocoa/

還有兩個相關工程

WebViewJavascriptBridge 與 GAJavaScript 值得大家慢慢研究。





相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.