陈桥驿站 陈桥驿站

Android WebView 获取HTML表单内容

--> Android 阅读 ( 94 ) 文章转载请注明来源!

前言

Android获取WebView里面表单的内容之前还真没接触过,昨天Android面试有面试官问到了,那么我就总结一下吧。

代码

HTML

JavaScript获取表单的内容,console一下打印下效果。

window.JSInterface.passParams(this.value);
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
    <form action="./">
        测试Android获取HTML表单数据
        <input type="text" name="testName" id="testId" />
    </form>
    <script type="text/javascript">
        document.getElementById("testId").oninput = function() {
            console.log(this.value);
            window.JSInterface.passParams(this.value);
        }
    </script>
  </body>
</html>

Android

class JSInterface {
    @JavascriptInterface
    public void passParams(String value) {
        Toast.makeText(MainActivity.this, value, Toast.LENGTH_SHORT).show();
    }
}
 webView.addJavascriptInterface(new JSInterface(), "JSInterface");
package net.cctv3.JobConclusion;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private WebView webView = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = findViewById(R.id.main_web);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }
        });
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.loadUrl("http://192.168.1.5:8080/Job");
        webView.addJavascriptInterface(new JSInterface(), "JSInterface");

    }

    class JSInterface {
        @JavascriptInterface
        public void passParams(String value) {
            Toast.makeText(MainActivity.this, value, Toast.LENGTH_SHORT).show();
        }
    }
}

本文基于《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权
文章链接:http://www.cctv3.net/archives/JSInterface.html (转载时请注明本文出处及文章链接)

Android
发表新评论
雷姆
拉姆