Calling Javascript function from Java (Webview android)

Asked

Viewed 803 times

0


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

The problem is that when the person is in the android (Webview) she clicks on the back button of the mobile phone and the application closes. I wanted when clicking back (on the button of the mobile phone) to call the function fechaCarrinho() web page, how do I do this?
Thanks in advance.

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 the Webview.evaluateJavascript, which will allow you to even catch the return ...; which will run on Webview itself:

Requires at least the 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);
    }
});
  • Our @Guilherme, was expecting a bug of seven heads here kkkkkk vlew I will do some tests later and I say if it worked.

  • All right @Brunoromualdo ? It worked?

  • Opa sorry friend was having problems on the pc so it took me to test and I forgot, but gave sure yes thanks for the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.