What will you learn in this post?

Crosswalk enables Web developers to develop native Android applications with our familiar HTML, CSS and JavaScript. In some cases, however, we need the help of Java code to do something JavaScript cannot. This post talks about how to call Java methods with JavaScript.

Calling native Java methods with JavaScript is not so particular with Crosswalk. Instead, it is a common need when developing using WebView on Android. But there are some minor differences for Crosswalk. This post may be of extra help for those Web developers who have limited experience with Android programming.

To get started with Crosswalk, you may refer to the official document.

Enable JavaScript

This step is very important! It won’t work without the following setting. Typically, we may want to declare them in onCreate of our main Activity.

mXWalkView = (XWalkView) findViewById(R.id.activity_main);
XWalkSettings webSettings = mXWalkView.getSettings();
webSettings.setJavaScriptEnabled(true);

Here, we use webSettings in org.xwalk.core.XWalkSettings instead of android.webkit.WebSettings, which is used in a standard Android application.

Declare a Class as Interface

Next, you need to declare a class as interface for all Java methods to be called uing JavaScript. You may declare them in a new Java file or as a member method of main activity. The following steps are in the former method.

Create a Java file named JsInterface.js and edit it as follows.

public class JsInterface {
	public JsInterface() {
	}
	
	@JavascriptInterface
	public String sayHello() {
		return "Hello World!";
	}
}

Caution: If you’ve set your targetSdkVersion to 17 or higher, you must add the @JavascriptInterface annotation to any method that you want available to your JavaScript (the method must also be public). If you do not provide the annotation, the method is not accessible by your web page when running on Android 4.2 or higher.

From developer.android.com

Add JavaScript Interface

In the main activity, add the following statement after setJavaScriptEnabled.

mXWalkView.addJavascriptInterface(new JsInterface(), "NativeInterface");

"NativeInterface" can be replaced with any name of object which contains the functions you would like to call with JavaScript later.

Call in JavaScript

mXWalkView.load("file:///android_asset/index.html", null);

In the index.html that will be loaded in main activity, we create a link that will call sayHello when clicked.

<a href="#" onclick="clicked()">Say Hello</a>
function clicked() {
    alert(NativeInterface.sayHello());
}

NativeInterface is the named in addJavascriptInterface in the last step.

You should now get the Hello World! information from alert.

Further Reading