Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Javascript method from within webview in Android

I am trying to call a javascript method defined in a html page from within webview. Function is not being called, and I don't see any errors in the log.

This is html file.

    </head>
    <body>
    <script type="text/javascript">
        function callJS(){
            $.ajax({url:"http://10.0.2.2:5010"});
        }
    </script>
    </body>
    </html>

And this is the Java code in a Activity in android

    WebView webView = new WebView(this);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl("file:///android_asset/temp.html");
    webView.loadUrl("javascript:callJS()");

Not sure how to debug this. When I add a onload=callJS() in body tag in html, I see the remote call being made. So, it looks like my HTML is fine,and it is being loaded into webview. However, webview is not able to call javascript method directly.

like image 365
user462455 Avatar asked Mar 10 '16 02:03

user462455


2 Answers

You should execute the javascript function when the page is loaded

webView.setWebViewClient(new WebViewClient() {
    public void onPageFinished(WebView view, String url) {
        webView.loadUrl("javascript:callJS()");
    }
});

When you put onload=callJS() means that the javascript function will be call when page is load. For debugging, you can put console.log("your text here") in your javascript function and you will get it in your android studio log. (Commonly with the tag I/chromium). Otherwise, you can use Remote Debugging on Android with Chrome. The documentation here https://developer.chrome.com/devtools/docs/remote-debugging.

like image 139
Pi Vincii Avatar answered Sep 30 '22 01:09

Pi Vincii


Please try this at once:

Activity code:

public class MainActivity extends AppCompatActivity {
 private WebView mWebView = null;
    private ProgressBar mLoading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.mWebView = (WebView)findViewById(R.id.wvPortal);
        mLoading = (ProgressBar) findViewById(R.id.pbLoading);
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setSupportZoom(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setSupportMultipleWindows(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.setWebChromeClient(new WebChromeClient());
       /* To keep page navigation within the WebView and hence within the app,
        we need to create a subclass of WebViewClient,and override its shouldOverrideUrlLoading(WebView webView, String url) method.*/
        WebViewClientImpl webViewClient = new WebViewClientImpl(this);
        mWebView.setWebViewClient(webViewClient);
        mWebView.loadUrl("file:///android_asset/www/index.html");
        WebSettings mWebSettings = mWebView.getSettings();
        mWebSettings.setJavaScriptEnabled(true);
        Log.d("Test 0","Interface calls");
        //calling javascript interface:
        // 1st.parameter is the JavaScript interface object itself.
        // 2nd.parameter is the name of the global JavaScript variable which the JavaScript interface object is bound to.
        mWebView.addJavascriptInterface(new AppJavaScriptProxy(this,mWebView), "androidAppProxy");

    }
}

AppJavaScriptProxy class for creationg interface :

public class AppJavaScriptProxy {
    private Activity activity = null;
    private WebView webView  = null;
    public AppJavaScriptProxy(Activity activity,WebView webview) {
        this.activity = activity;
        this.webView  = webview;
        Log.d("Test 1","in Interface");
    }

    @JavascriptInterface
    public void showMessage(final String message) {
        Log.d("from javascript", "" + message);
        final Activity theActivity = this.activity;
        final WebView theWebView = this.webView;
        this.activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!theWebView.getUrl().startsWith("file:///android_asset/www/index.html")) {
                    return;
                }
                Toast toast = Toast.makeText(
                        theActivity.getApplicationContext(),
                        message,
                        Toast.LENGTH_SHORT);
                toast.show();
            }
        });
    }
}

Index.html call this script in html page.

<input type="button" value="call Methode" onClick="showMessage("Message from JavaScript")" />
<script>
    if(typeof androidAppProxy !== "undefined"){
    androidAppProxy.showMessage("Message from JavaScript");
} else {
    alert("Running outside Android app");
}
</script>

call this script on any button click on webview index page. Ref. Building webapps in webview

If above code snippet would helps you please vote my answer. Thanks!

like image 36
Sandeep Devhare Avatar answered Sep 30 '22 03:09

Sandeep Devhare