[英]Objective-C method from javascript is not called
我有一个UIWebView
,其中包含带有JS功能的按钮,但是按我的意图,仅在加载页面而不是在按下的按钮上调用委托方法。
问题是什么?
聚苯乙烯
我正在模拟器上测试。
在.h中:
@interface MyViewController : UIViewController <UIWebViewDelegate>{
UIWebView *webView;
}
@property (strong, nonatomic) IBOutlet UIWebView *webView;
在.m中:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *myHTML = @"<!DOCTYPE html><html><head><script type=\"text/javascript\">
function myFunction(){document.location = \"myapp:\" + \"myfunction:\"
+ param1 + \":\" + param2;}</script></head><body><button onclick=\
"myFunction()\">Try it</button><p>By clicking the button above,
a function will be called.</p></body></html>";
[webView loadHTMLString:myHTML baseURL:nil];
webView.delegate = self;
}
- (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.
}
以这种方式测试对我有效
NSString *myHTML = @"<!DOCTYPE html><html><head>" "<script type='text/javascript'>function myFunction(){alert('ciao');document.location = 'myapp:myfunction:param1:param2';}
</script>"
"</head><body><button onclick='myFunction()'>Try it</button>"
"<p>By clicking the button above,a function will be called.</p></body></html>";
您的错误应如下
document.location = \"myapp:\" + \"myfunction:\" + param1 + \":\" + param2;
你应该写
document.location =\"myapp:myfunction:param1:param2\";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.