Call Java function from JavaScript over Android WebView

If you want to get a return value from Javascript in Android, so here is the solution:

1- Start building the Class of interface as below:
public class WebAppInterface {
    Context mContext;

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

    /** Show a toast from the web page */ 
    @JavascriptInterface 
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
}
 
2- Get a reference for the WebView object:
webView = (WebView) findViewById(R.id.webView); 
 
3- Enable the javascript for the WebView:
webView.getSettings().setJavaScriptEnabled(true); 
 
4- Add the interface to the WebView:
WebAppInterface WebAppInterface = new WebAppInterface(this);
webView.addJavascriptInterface(WebAppInterface, "WebAppInterface");
 
5- Then you can call that method from javascript:
WebAppInterface.showToast(THE_VALUE_YOU_NEED_TO_PASS); 


You can get an example from this link:


ليست هناك تعليقات:

إرسال تعليق

---- أتشرف بتعليقاتكم ----