2

I know you can define javascript interfaces for use in webviews. Can you go the other way and call javascript functions in android on your webviews?

for example

        WebView myWebView = (WebView) findViewById(R.id.webview);
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        myWebView.addJavascriptInterface(new WebAppInterface(this),
                "Android");
        myWebView.loadUrl("http://www.mytest.com/whatever.php?");

        String formValue = myWebView.fireJavascriptFunction("getFormInput");

and my html page would have the following javascript function

function getFormInput(){
    return $("#myInput").val();
}

The idea would be to trigger the getFormInput() function from a native onclick handler of a native button.

David
  • 10,418
  • 17
  • 72
  • 122

2 Answers2

0

A simple google search for "android webview call javascript function" gives you many examples. Here is one. However, you can not return a value from this call. If you need a return value, then you can implement a callback method in your JavaScript interface Object.

Community
  • 1
  • 1
SimonSays
  • 10,867
  • 7
  • 44
  • 59
0

You can simply call myWebView.loadUrl("javascript:getFormInput()"); in order to run the function.

However getting the result from a javascript function that runs in a webview, and using it in the java code, is much more complicated than that. Getting info from a WebView at all is complicated. You can get some more info on that in this post:

How do I get the web page contents from a WebView?

Community
  • 1
  • 1
tbkn23
  • 5,205
  • 8
  • 26
  • 46