Call JavaScript function by Java (Webview android)

0


I have a simple question to understand but I have not yet found a solution.
I have a Webview in my MainActivity where a responsive WebSite is created that I created, in this WebSite I have a shopping cart that clicking on it opens a div with user items, and at the top right of div a button with an 'X' that when clicked calls a function fechaCarrinho() in javascript .

The problem is that when the person is in android (WebView) he clicks the back button on the phone and the application closes. I wanted to click on the back button (on the cell button) to call the fechaCarrinho() function of the Web page, how do I do this?
Thank you in advance.

    
asked by anonymous 25.09.2017 / 16:20

1 answer

1

There are two ways

Protocol javascript:

You can perform your function like this:

webView.loadUrl("javascript:fechaCarrinho()");

WebView.evaluateJavascript

Or you can use WebView.evaluateJavascript , which will allow you to even get the return ...; that will run in WebView itself:

  

Requires at least API 19 , if lower will not work

webView.evaluateJavascript(javascript, new ValueCallback<String>()
{
    @Override
    public void onReceiveValue(String value)
    {
        //Pega o valor do return de "fechaCarrinho" se você deseja
        Log.d(tag, value);
    }
});
    
25.09.2017 / 16:23