Get JavaScript variable in webview in Android

6.5k views Asked by At

I am working on an e-learning project using SCROM APIs, but now I got stuck at one point: how to get server-side JavaScript value in my core Android activity IN WEBVIEW from scrom API?

I am trying below code:

 public class MyJavaScriptInterface   
    {  Context mContext;

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


    /** retrieve the ids */
    public void getbookmark(final String bookmarkId) {

        webView.loadUrl("javascript:Android.getbookmark(BOOKMARKED_PAGE);");
        //getWindow().requestFeature();


    }

        @SuppressWarnings("unused")  
        public void showHTML(String html)  
        {  
           new AlertDialog.Builder(myApp)  
                .setTitle("HTML")  
                .setMessage(html)  
                .setPositiveButton(android.R.string.ok, null)  
            .setCancelable(false)  
            .create()  
            .show(); 
        }  
    }  

Do I have to take the value of onpagefinished() function of WebView?

2

There are 2 answers

0
J.K On

you can use javascript bridge for your requirement you can find the source , this too

0
Matt Gaunt On

You'll want to add a javascript interface:

mWebView.addJavascriptInterface(new MyJavaScriptInterface(getApplicationContent(), "JSInterface");

Add a method in your interface you want to call and ensure you have the @JavascriptInterface annotation so Android makes it callable:

@JavascriptInterface
public void showHTML(String html)  
{  
   new AlertDialog.Builder(myApp)  
        .setTitle("HTML")  
        .setMessage(html)  
        .setPositiveButton(android.R.string.ok, null)  
    .setCancelable(false)  
    .create()  
    .show(); 
} 

Then follow the approach you are doing at the moment of calling a method in javascript:

webView.loadUrl("javascript:Android.getbookmark(BOOKMARKED_PAGE);");

And the javascript method would look something like:

window.Android.getbookmark = function(variable) {
    var returnValue = getSomeValue(variable);

    if(!window.JSInterface) {
        console.error('window.JSInterface not defined - Did you inject the javascript interface in the native app?');
    }

    window.JSInterface.showHTML(returnValue);
};

Notice the reason we have window.JSInterface is because we added it with that name in:

mWebView.addJavascriptInterface(new MyJavaScriptInterface(getApplicationContent(), "JSInterface");

NOTE: In KitKat it is more efficient to use evaluateJavascript() than loadUrl, simplest form shown below, allow you can pass in a callback to get a return value (Demo in the sample code)

webView.evaluateJavascript("Android.getbookmark(BOOKMARKED_PAGE);", null);

There is a full JS Interface sample here which includes the new API's in KitKat: https://github.com/GoogleChrome/chromium-webview-samples