JavaScript Android Interface WebView Call Java function From JS onclick

1

I have all this code but I can not get JavaScript Interface to work with an html button to execute a function in java that starts an application with the intent method.

I'm using Webview chrome client, an index.html file located in / main / assets that contains the buttons, if anyone can help me, it's urgent thanks.

// Enabling JS
mWebView.getSettings().setJavaScriptEnabled(true);

myWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");

// Java and Javascript interfacing
mWebView.addJavascriptInterface(new JavascriptInterface(), "JsInterface");



// outside oncreate
public class JavaScriptInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    JavaScriptInterface(Context c) {
        mContext = c;
    }

    /** Show a toast from the web page */
    public void FacebookIntentShare(Intent) {
        Facebook Intent
    }
}



<a href="#" onclick="FacebookIntentShare()">Iniciar Facebook</a>

  <button type="button" onclick="FacebookIntentShare();">Iniciar 
  Facebook</button>

<script type="text/javascript">
function FacebookIntentShare(){
   //return value to Android 
   codigo que llame a una funcion de java...
la funcion de java debe lanzar un intent send to
}
</script>
    
asked by MBS.corp 28.12.2017 в 17:34
source

1 answer

-1

If you define your interface in this way, it would be called "Android" :

JavaScriptInterface jsInterface = new JavaScriptInterface();
myWebView.addJavascriptInterface(jsInterface, "Android");

obviously the method you want to call must be declared in the interface, important to declare @JavascriptInterface :

public class JavaScriptInterface {

    @JavascriptInterface
    public void FacebookIntentShare() {
     ...
     ...
    }

}

Therefore when you make the call of the methods within the HTML code you must specify that it is a method of the interface "Android" , for example:

<a href="#" onclick="Android.FacebookIntentShare()">Iniciar Facebook</a>

or simply:

   <a href="#" onclick="FacebookIntentShare()">Iniciar Facebook</a>

Example: Android Javascript Interface

    
answered by 28.12.2017 / 20:30
source