uiwebview中的javascript事件处理程序

Roy*_*nto 15 iphone xcode objective-c

我在我的iPhone应用程序中显示一个UIWebView.在UIWebView中,我显示的HTML页面也有JavaScript.我想在HTML页面中单击一个按钮时调用方法(X代码).

我怎样才能做到这一点.谢谢

cdu*_*uhn 38

如果我正确理解你的问题,你想从你的javascript onClick事件处理程序调用Objective C方法UIWebView.这样做的方法是将浏览器重定向到您的javascript代码中具有自定义方案的URL,如下所示:

function buttonClicked() {
    window.location.href = "yourapp://buttonClicked";
}
Run Code Online (Sandbox Code Playgroud)

回到Objective C,声明你的视图控制器符合UIWebViewDelegate协议,

@interface DTWebViewController : DTViewController <UIWebViewDelegate> {
...
Run Code Online (Sandbox Code Playgroud)

将您的控制器设置为Web视图的委托,

- (void)viewDidLoad {
    [super viewDidLoad];
    self.webView.delegate = self;
}
Run Code Online (Sandbox Code Playgroud)

并在加载之前截取URL,如下所示:

- (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
    }
}
Run Code Online (Sandbox Code Playgroud)