Kit
Kit

Reputation: 359

It is possible to call a javascript function in android?

I know that I can do functions in android and call they throught javascript, but I don't know if it is possible to call a javascript functions inside android (java).

For example, I have a little app in android that open a webview and inside the site I want to, when user click on back button of device, the webview call a javascript function to go back to the last action (of the site) and if it doesn't have an action it closes the app instead of going to main activity.

I know that I can use something like:

@Override
public void onBackPressed() {
   if (mWebView.canGoBack()) {
       mWebView.goBack();
   } else {
       finish();
   }
}

but it doesn't work in my case and I need to call a js function.

Someone can help?

Upvotes: 1

Views: 902

Answers (2)

TKoL
TKoL

Reputation: 13892

I believe you can use

WebView webView = (WebView) findViewById(R.id.webview);
webView.setWebChromeClient(new MyCustomChromeClient(this));
webView.getSettings().setJavaScriptEnabled(true);
webView.evaluateJavascript("globalJavascriptFunction();", null);

https://developer.android.com/reference/android/webkit/WebView#evaluateJavascript(java.lang.String,%20android.webkit.ValueCallback%3Cjava.lang.String%3E)

The second argument is a callback.


[edit]

To get a value back from the javascript, you can do something like this:

webView.evaluateJavascript("globalJavascriptFunction();", new ValueCallback<String>() {
    @Override
    public void onReceiveValue(String result) { 
       // result is the return value of globalJavascriptFunction()
       // you'll have to do some testing inside here to figure out exactly how result gets sent back for your usecase
    }
});

Upvotes: 3

Sanket Vekariya
Sanket Vekariya

Reputation: 2956

There might be something missing... Go through the below code...

WebView webView = (WebView) findViewById(R.id.webview);
webView.setWebChromeClient(new MyCustomChromeClient(this));
webView.setWebViewClient(new MyCustomWebViewClient(this));
webView.clearCache(true);
webView.clearHistory();
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

...

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    finish();
                }
                return true;
        }

    }
    return super.onKeyDown(keyCode, event);
}

Upvotes: 2

Related Questions