问题
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?
回答1:
If you are only using XWalkView as an embedded view, the addJavascriptInterface
is sufficient to inject Java object into XWalkView(JavaScript), which is just like the addJavascriptInterface
in android.webkit.WebView:
https://crosswalk-project.org/apis/embeddingapidocs_v2/reference/org/xwalk/core/XWalkView.html
http://developer.android.com/guide/webapps/webview.html#BindingJavaScript
回答2:
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.
来源:https://stackoverflow.com/questions/25478434/crosswalk-call-java-method-from-javascript