android通过WebView的evaluateJavascript调用JS

时间:2025-01-17 19:05:22
  • 因为该方法的执行不会使页面刷新,而方法(loadUrl )的执行则会使页面刷新。
  • Android 4.4 后才可使用
    public class MainActivity extends Activity {
        WebView webView;
        Button buttonLeft, buttonRight;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            (savedInstanceState);
            setContentView(.activity_main);
     
            webView = findViewById();
            buttonLeft = findViewById();
            buttonRight = findViewById();
     
            WebSettings webSettings = ();
            //允许使用JS
            (true);
            // 设置允许JS弹窗
            (true);
     
            ("file:///android_asset/");
     
            (new () {
                @Override
                public void onClick(View view) {
                    (new Runnable() {
                        @Override
                        public void run() {
                            ("javascript:callJS()", new ValueCallback<String>() {
                                @Override
                                public void onReceiveValue(String s) {
                                    //将button显示的文字改成JS返回的字符串
                                    (s);
                                }
                            });
                        }
                    });
                }
            });
     
            (new WebChromeClient() {
     
                @Override
                public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                     b = new ();
                    ("alert1");
                    (message);
                    (, new () {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            ();
                        }
                    });
                    (false);
                    ().show();
                    return true;
                }
            });
        }
    }