2

Really do not have any ideal why this doesn't work. Basically, I am trying to do this.

 public void testJS() {
        final WebView webView = (WebView) findViewById(web);
//        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new JSInterface(webView), "sample");
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        /* Do whatever you need here */
                Log.e("chrome", "asdf");
                return super.onJsAlert(view, url, message, result);
            }


        });
        webView.loadUrl("javascript:window.sample.doEchoTest();void(0);");
    }

and this is the JSInterface

   public class JSInterface {
        WebView mAppView;

        public JSInterface(WebView appView) {
            this.mAppView = appView;
        }

        public void doEchoTest() {
            Log.e("sample", "test details");
            Toast toast = Toast.makeText(mAppView.getContext(), "sample test details", Toast.LENGTH_SHORT);
            toast.show();
        }
    }

the javascript code never runs.

basic functions like alert works :

webView.loadUrl("javascript:alert('sample')");

why is webView.loadUrl("javascript:window.sample.doEchoTest();void(0);"); not working ?

1 Answer 1

1

Just browsing for a different answer, a guess at this would be that you haven't exposed it to be accessible from JS. You need to do so explicitly for each method as so:

@JavascriptInterface
public void doEchoTest() {
            Log.e("sample", "test details");
            Toast toast = Toast.makeText(mAppView.getContext(), "sample test details", Toast.LENGTH_SHORT);
            toast.show();
        }
Sign up to request clarification or add additional context in comments.

1 Comment

Welcome to Stack Overflow! Please feel free to take a tour of the site, and if you need additional help with the site, check this out. Oh, and if you ever run into issues that the help page doesn't cover, feel free to ask on meta.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.