ios里面怎样监听js的事件
1个回答
2016-05-07 · 百度知道合伙人官方认证企业
育知同创教育
1【专注:Python+人工智能|Java大数据|HTML5培训】 2【免费提供名师直播课堂、公开课及视频教程】 3【地址:北京市昌平区三旗百汇物美大卖场2层,微信公众号:yuzhitc】
向TA提问
关注
展开全部
在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.
大概思路是:在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.
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询