android通过WebView的evaluateJavascript()调用JS

 

  1. 因为该方法的执行不会使页面刷新,而方法(loadUrl )的执行则会使页面刷新。
  2. Android 4.4 后才可使用

同:https://www.cnblogs.com/liuyj-vv/p/9583831.html

仅java代码不同,可以接收JS函数的返回值

public class MainActivity extends Activity {
    WebView webView;
    Button buttonLeft, buttonRight;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = findViewById(R.id.webview);
        buttonLeft = findViewById(R.id.btnLeft);
        buttonRight = findViewById(R.id.btnRight);

        WebSettings webSettings = webView.getSettings();
        //允许使用JS
        webSettings.setJavaScriptEnabled(true);
        // 设置允许JS弹窗
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

        webView.loadUrl("file:///android_asset/index.html");

        buttonLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                webView.post(new Runnable() {
                    @Override
                    public void run() {
                        webView.evaluateJavascript("javascript:callJS()", new ValueCallback() {
                            @Override
                            public void onReceiveValue(String s) {
                                //将button显示的文字改成JS返回的字符串
                                buttonLeft.setText(s);
                            }
                        });
                    }
                });
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this);
                b.setTitle("alert1");
                b.setMessage(message);
                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        result.confirm();
                    }
                });
                b.setCancelable(false);
                b.create().show();
                return true;
            }
        });
    }
}

  

 

转载于:https://www.cnblogs.com/liuyj-vv/p/9583871.html

你可能感兴趣的:(android通过WebView的evaluateJavascript()调用JS)