uiwebview中的javascript事件处理程序 [英] javascript event Handler in uiwebview
问题描述
我在iPhone应用程序中显示一个UIWebView。在UIWebView中,我也显示了具有JavaScript的HTML页面。我想在HTML页面中单击一个按钮时调用方法(X代码)。
I am displaying one UIWebView in my iPhone application. In UIWebView I am displaying HTML page which has JavaScript also. I want to call method(of X Code) when one button is clicked in HTML page.
我该怎么做。
谢谢
How can I do this. Thanks
推荐答案
如果我理解你的问题,你想从javascript <$调用Objective C方法c $ c> onClick UIWebView
中的事件处理程序。这样做的方法是将浏览器重定向到javascript代码中带有自定义方案的URL,如下所示:
If I understand your question correctly, you want to call an Objective C method from a javascript onClick
event handler in your UIWebView
. The way to do that is to redirect the browser to a URL with a custom scheme in your javascript code like this:
function buttonClicked() {
window.location.href = "yourapp://buttonClicked";
}
返回目标C,声明您的视图控制器符合 UIWebViewDelegate
协议,
Back in Objective C, declare that your view controller conforms to the UIWebViewDelegate
protocol,
@interface DTWebViewController : DTViewController <UIWebViewDelegate> {
...
将您的控制器设置为Web视图的委托,
set your controller as the web view's delegate,
- (void)viewDidLoad {
[super viewDidLoad];
self.webView.delegate = self;
}
并在加载之前截取网址:
and intercept the URL before it loads like this:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if ([[request.URL scheme] isEqual:@"yourapp"]) {
if ([[request.URL host] isEqual:@"buttonClicked"]) {
[self callYourMethodHere];
}
return NO; // Tells the webView not to load the URL
}
else {
return YES; // Tells the webView to go ahead and load the URL
}
}
这篇关于uiwebview中的javascript事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!