Search code examples
javascriptiphonecocoa-touchuiwebviewuiwebviewdelegate

Objective-C method from javascript is not called


I have a UIWebView that contains button with JS function, but the delegate method is called only on load page and not on the button pressed, as I intended.

What is the problem?

P.S.

I am testing on simulator.

in .h:

@interface MyViewController : UIViewController <UIWebViewDelegate>{
    UIWebView *webView;
}
@property (strong, nonatomic) IBOutlet UIWebView *webView;

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

Solution

  • Test in this way, works to me

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

    your error should be as follows

    document.location = \"myapp:\" + \"myfunction:\" + param1 + \":\" + param2;
    

    you should write instead

    document.location =\"myapp:myfunction:param1:param2\";