Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crosswalk call Java method from JavaScript

I'm using crosswalk now. I need to call a Java method when a user clicks a button in the HTML, which may look like:

<a href="#" onclick="callJava()">Start</a>

I'm not sure if Crosswalk extension is what I wanted, which seems to be so heavy-weighted just for calling a Java function.

Is there a simpler way to do this? Or should I use Cordova with Crosswalk in this case?

like image 777
Ovilia Avatar asked Dec 14 '22 20:12

Ovilia


1 Answers

Here is about how to call java function with js in the crosswalk XWalkView. How to use XWalkView refer this answer.

References:

crosswalk-calling-java-methods-with-javascript

XWalkView manual

Below is the process to call java from js, and notices.

add this to activity you XWalkView in

webSettings.setJavaScriptEnabled(true);
mXWalkView.addJavascriptInterface(new JsInterface(), "NativeInterface");

and this, you also make it a class

public class JsInterface {
    public JsInterface() {
    }

    @JavascriptInterface
    public void act() {
        //do something
    }
}

and in the html page

<button onclick="NativeInterface.act()">Call Java Here</button>

when you import JavascriptInterface, take care, make sure you imported the exact one.

import org.xwalk.core.JavascriptInterface;

Not this one, this is for webview

import android.webkit.JavascriptInterface;

If you import this one, this will cause no action when you operation on the page and below error in your android studio.

12-02 13:24:49.921 12376-12376/com.xxxxxx.app E/chromium: [ERROR:xwalk_autofill_client.cc(121)] Not implemented reached in virtual void xwalk::XWalkAutofillClient::OnFirstUserGestureObserved()

Usually when you import the JavascriptInterface, the first one is what we want just like below pic shows.

But sometime when you change from webview to XWalkView, you may forget to change the JavascriptInterface.

enter image description here

like image 61
LF00 Avatar answered Dec 17 '22 10:12

LF00