Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
355 views
Welcome To Ask or Share your Answers For Others

1 Answer

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";
}

Back in Objective C, declare that your view controller conforms to the UIWebViewDelegate protocol,

@interface DTWebViewController : DTViewController <UIWebViewDelegate> {
...

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
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...