Tuesday, May 7, 2013

UIWebview. How to call javascript functions from objective-c

I wrote about this long time ago but only to remember how simple it is.

1) Write the javascript function in your HTML file

function callMePlease () {
    // Your code here
}


2) Use this line to call the function from Objective-C using your  UIWebView object.
[webview stringByEvaluatingJavaScriptFromString:@"callMePlease()"];

For example if we only want to execute some javascript code in our webview we can use:

NSInteger pos = 100;NSString* s=[[NSString alloc] initWithFormat:@"window.scrollTo(%i, 0)",pos];[webViewMenu stringByEvaluatingJavaScriptFromString:s];

If we want to call a Objective-C function from our JavaScript code... things are a little bit more difficult:

1) In Objective C we must have

- someFunctionOnInit {
    
    webView = [[UIWebView alloc] init];
    // Register the UIWebViewDelegate in order to shouldStartLoadWithRequest to be called (next function)
    webView.delegate = self;
    
}

// This function is called on all location change :
- (BOOL)webView:(UIWebView *)webView2
shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType {
    
    // Intercept custom location change, URL begins with "js-call:"
    if ([[[request URL] absoluteString] hasPrefix:@"js-call:"]) {
        
        // Extract the selector name from the URL
        NSArray *components = [requestString componentsSeparatedByString:@":"];
        NSString *function = [components objectAtIndex:1];
        
        // Call the given selector
        [self performSelector:NSSelectorFromString(functionName)];
        
        // Cancel the location change
        return NO;
    }
    
    // Accept this location change
    return YES;
    
}

- (void)myObjectiveCFunction {
    
    // Do whatever you want!
    
}

There are another ways to do the same but it is enough for today. For more information check this.


Cheers

No comments:

Post a Comment