How to Call Native Iphone/Android function from Javascript?
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);
}