Friday, December 16, 2011

Using javascript in webview to call native code

We will define two js functions in android

  • goToHome
  • showToast

for javacript calls from the webview.

You would call the functions like
<script type="text/javascript">
  window.jsinterface.goToHome()
  window.jsinterface.showToast()
</script>
Define the following in your android activity as an inner class.
public class JSInterface {
public void goToHome() {
Intent i = new Intent(getApplicationContext(), Home.class);
startActivity(i);
}
public void showToast(final String msg) { Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
}
In your onCreate function, intialize the webview similar to below:
WebView mWebView = (WebView) findViewById(R.id.webview);
mWebView.setVisibility(View.GONE);
mWebView.addJavascriptInterface(new JSInterface(), "jsinterface");
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int progress) {
Logger.v("webview", String.format("progress changed: %d", progress));
if (progress == 100) {
// webpage loaded completely
} else {
// webpage is loading
}
}
//@Override
public boolean onJsAlert(WebView view, String url,
String message, JsResult result) {
// if you do js alerts, this will show them as toast
Toast.makeText(getBaseContext(), message, Toast.LENGTH_SHORT).show();
result.confirm();
return true;
}
});

Basicly, that's it!

No comments:

Post a Comment