安卓端调 Js 方法

mac2025-02-11  12

activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" tools:context=".MainActivity"> <WebView android:id="@+id/web_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="gone"> </WebView> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="调用JS代码"/> </LinearLayout>

 

MainActivity.java

package com.example.webviewtest; public class MainActivity extends AppCompatActivity { private WebView mWebView; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mWebView = findViewById(R.id.web_view); WebSettings webSettings = mWebView.getSettings(); //设置与JS交互的权限 webSettings.setJavaScriptEnabled(true); //设置允许JS弹窗 webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //先载入JS代码 mWebView.loadUrl("http://192.168.17.xx:8081/hello.html"); button = findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //通过Handler发送消息 mWebView.post(new Runnable() { @Override public void run() { //调用Js中的 hello()方法 mWebView.loadUrl("javascript:hello()"); } }); } }); //由于设置了弹窗检验调用结果,所以需要支持js对话框 //webview只是载体,内容的渲染需要使用webviewChromClient类去实现 //通过设置WebChromeClient对象处理JavaScript的对话框 //设置响应js的Alert()函数 mWebView.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("Alert"); b.setMessage(message); b.setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { result.confirm(); } }); b.setCancelable(false); b.create().show(); return true; } }); } }

 

服务器端的 Js 方法

<script> function hello() { alert("Hello World!"); } </script>

 

最新回复(0)