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 ?

Belvi Nosakhare
  • 3,107
  • 5
  • 32
  • 65

1 Answers1

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();
        }
EE Chris
  • 11
  • 1
  • Welcome to Stack Overflow! Please feel free to take a [tour](//stackoverflow.com/tour) of the site, and if you need additional help with the site, check [this](//stackoverflow.com/help) out. Oh, and if you ever run into issues that the help page doesn't cover, feel free to ask on [meta](//meta.stackoverflow.com/). – Claudia Jun 20 '17 at 16:28