Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crosswalk call js function from java on android

I m trying to use crosswalk runtime in my android app. I tried this on android 4+.

I got some js & html codes and it worked perfect for me. But it is not working like android webview. In the webview i can call javascript functions from java code. But i couldnt find any option in crosswalk. Any idea?

Thanks

like image 398
gokhangokce Avatar asked Nov 30 '22 01:11

gokhangokce


1 Answers

In Android Studio inside app/module/lib level build.gradle add this to dependencies:

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'org.xwalk:xwalk_core_library:12.41.296.5'}

Sync Project

create xml layout resource

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<org.xwalk.core.XWalkView
    android:id="@+id/xwalkWebView"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#000000"
    />

</LinearLayout>

In activity onCreate or called by it

//        Don't know how this helps if the preferences are connected?
XWalkPreferences.setValue("enable-javascript", true);
XWalkPreferences.setValue(XWalkPreferences.REMOTE_DEBUGGING, true);

xWalkView=(XWalkView)findViewById(R.id.xwalkWebView);
xWalkView.addJavascriptInterface(new JS_Bind(this, xWalkView),"Android");

xWalkView.clearCache(true);
xWalkView.load(COM_URL, null);

create class JS_Bind:

public class JS_Bind {
    private static final String TAG = "JS_Bind";
    private Context context;
    private XWalkView xWalkWebView;

    public JS_Bind(Context c, XWalkView xWalkWebView) {
        context = c;
        this.xWalkWebView = xWalkWebView;
    }

    @JavascriptInterface
    public void showToast(String toast) {
        Log.d(TAG, "showToast(String toast)");
        Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
    }
}

in web Java script call the function thus:

Android.showToast(toast);

make sure you import the correct xwalk @JavaScripInterface decorator instead of the standard web view decorator.

like image 94
Rubber Duck Avatar answered Dec 05 '22 02:12

Rubber Duck