在iOS開發之Objective-C與JavaScript互動操作 中我們可以通過stringByEvaluatingJavaScriptFromString 去實現在obj-C中擷取到相關節點屬性,添加javascript代碼等功能。但是我們如何監聽到javascript的響應事件呢。在MAC OS中有效API去實現,但iPhone沒有,但我們有一個技巧途徑:
大概思路是:在JavaScript事件響應時,通過設定document.location,這會引發webview的一個delegate方法,從而實現發送通知的效果,即達到監聽的目的。
1、在javascript與webView之間定一個協議約定:
myapp:myfunction:myparam1:myparam2
2、在javascript中添加代碼:
document.location = "myapp:" + "myfunction:" + param1 + ":" + param2;
3、在webView的delegate方法webView:shouldStartLoadWithRequest:navigationType: 添加
- (BOOL)webView:(UIWebView *)webView2 shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSString *requestString = [[request URL] absoluteString]; NSArray *components = [requestString componentsSeparatedByString:@":"]; if ([components count] > 1 && [(NSString *)[components objectAtIndex:0] isEqualToString:@"myapp"]) { if([(NSString *)[components objectAtIndex:1] isEqualToString:@"myfunction"]) { NSLog([components objectAtIndex:2]); // param1 NSLog([components objectAtIndex:3]); // param2 // Call your method in Objective-C method using the above... } return NO; } return YES; // Return YES to make sure regular navigation works as expected.}
check:http://stackoverflow.com/questions/5671742/send-a-notification-from-javascript-in-uiwebview-to-objectivec
http://www.codingventures.com/2008/12/using-uiwebview-to-render-svg-files/