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.
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;
}
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
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);
}
}
In javascript you use the javascript interface:
if (window.AndroidBridge) {
window.AndroidBridge.changeNavbarBackground(color);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With