2

真的没有任何理想为什么这不起作用。基本上,我正在尝试这样做。

 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);");
    }

这是 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();
        }
    }

javascript 代码永远不会运行。

警报等基本功能有效:

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

为什么webView.loadUrl("javascript:window.sample.doEchoTest();void(0);"); 不工作?

4

1 回答 1

1

只是浏览不同的答案,对此的猜测是您尚未将其公开为可从 JS 访问。您需要为每个方法明确地这样做:

@JavascriptInterface
public void doEchoTest() {
            Log.e("sample", "test details");
            Toast toast = Toast.makeText(mAppView.getContext(), "sample test details", Toast.LENGTH_SHORT);
            toast.show();
        }
于 2017-06-20T16:10:06.307 回答