Billda
Billda

Reputation: 5987

Calling javascript function in android kitkat

Since upgrading my nexus 4 to Android kitkat, my application stopped working. I was using javascript methods in webview but now my methods are not called. This is how i setup webview and load my javascripts:

 mWebview.getSettings().setJavaScriptEnabled(true);
 JavaScriptInterface jsi = new JavaScriptInterface(mCtx);
 mWebview.addJavascriptInterface(jsi, ANDROID_BRIDGE);
 mWebview.setWebViewClient(new WebClient());
 mWebview.setWebChromeClient(new OwnChromeClient());
 mWebview.setWebContentsDebuggingEnabled(true);
 mWebview.loadUrl("about:blank"); //load dummy url to onPageFinished called in webViewClient

and my webClient:

public class WebClient extends WebViewClient {


        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            Log.e(WebClient.class.getSimpleName(), description + " code "
                    + errorCode);
        }

        /**
         * Load javascript into webview
         */
        @Override
        public void onPageFinished(WebView view, String url) {
            ECalcMarblesWrapper wrapper = new ECalcMarblesWrapper(mCtx);
            String javascripts = wrapper.getJavascripts();

            String content = String.format(jsHtmlContainer, javascripts,
                    jsHelpFunctions);

            view.loadUrl("javascript: " + content);
        }
    }

all loading methods are called but when i call any of javascript methods, this error is printed out to console:

Uncaught ReferenceError: initForm is not defined

where initForm is my javascript method.

On api 18 application is doing just fine, i have javascript annotation in my methods

Upvotes: 1

Views: 3604

Answers (2)

SetiZ
SetiZ

Reputation: 51

everything changes in Android kitkat for webview and javascript. you need to use evaluateJavascript()

check here: https://developer.android.com/guide/webapps/migrating.html and here: https://developer.android.com/reference/android/webkit/WebView.html#evaluateJavascript(java.lang.String, android.webkit.ValueCallback)

Upvotes: 0

M D
M D

Reputation: 47807

If the target version of the application is set to 17 or higher you need to add annotation @JavascriptInterface above each method you want to export to the web view.

Upvotes: 4

Related Questions