Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Call Native Iphone/Android function from Javascript?

I am using Web View both in Iphone and Android. In Android, I use create a variable to call native Andriod functions/methods. But I have not able to find something similar in Iphone. So, how to call a native Iphone function from JavaScript.

like image 421
Imran Qadir Baksh - Baloch Avatar asked Jan 06 '13 12:01

Imran Qadir Baksh - Baloch


1 Answers

iOS

In iOS you could use a custom url scheme by implementing shouldStartLoadWithRequest. If I would by example want to change the toolbar's tint color:

ViewController.h

@property (strong, nonatomic) IBOutlet UIToolbar *toolbar;

ViewController.m

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSURL *url = request.URL;
    NSString *scheme = [url scheme];

    if ([scheme isEqualToString:@"color"]) {
        self.toolbar.tintColor = [self colorWithHexString:url.host];
    }

    return YES;
}

Javascript

In javascript you just change window.location, which will launch a fire and forget:

window.location = 'color://' + color;

Just chain your parameters like:

window.location = 'myscheme://param1/' + value1 + '/param2/' + value2;

Just make sure you use encodeURIComponent to encode your parameters (to create a valid url).

More info

Android

In Android you add a javascript interface:

    WebView webView = getWebView();
    webView.loadUrl("http://localhost:8080");
    // must be after loadUrl on lower apis
    webView.addJavascriptInterface(new AndroidBridge(this), "AndroidBridge");

...

public class AndroidBridge {

    private MainActivity activity;

    public AndroidBridge(MainActivity activity) {
        this.activity = activity;
    }

    @JavascriptInterface
    public void changeNavbarBackground(String color) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
        Log.i(getClass().getSimpleName(), "changeNavbarBackground " + color);

        Field f = R.color.class.getField(color);
        final int col = (Integer) f.get(null);

        activity.changeNavbarBackground(col);
    }
}

Javascript

In javascript you use the javascript interface:

if (window.AndroidBridge) {
            window.AndroidBridge.changeNavbarBackground(color);
}
like image 103
asgoth Avatar answered Oct 18 '22 01:10

asgoth