大概思路是:在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.
}