- 因为该方法的执行不会使页面刷新,而方法(loadUrl )的执行则会使页面刷新。
- Android 4.4 后才可使用
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<String>() { @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; } }); } }
android通过WebView的evaluateJavascript()调用JS
最新推荐文章于 2024-09-29 13:57:16 发布