Android Webview 獲取網頁form 提交的資料
阿新 • • 發佈:2019-02-04
android webview 獲取網頁form提交的資料
public class WebActivity extends BaseActivity { @ViewInject(R.id.web_view) private WebView mWebView; @ViewInject(R.id.tv_title_center) private TextView mTitle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_faq); ViewUtils.inject(this); String title = getIntent().getStringExtra("title"); if (!TextUtils.isEmpty(title)) { mTitle.setText(title); } else { findViewById(R.id.layout_title).setVisibility(View.GONE); } mWebView.addJavascriptInterface(new JavaScriptInterface(), "JSInterface"); String url = getIntent().getStringExtra("url"); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.loadUrl(url); mWebView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { handler.proceed(); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); view.loadUrl("javascript:" + buildInjection()); } }); } private String buildInjection() { StringBuilder sb = new StringBuilder(); sb.append("document.getElementsByTagName('form')[0].onsubmit = function () {"); sb.append("var applyname, pccc_applyname;var str = '';"); sb.append("var inputs = document.getElementsByTagName('input');"); sb.append("for (var i = 0; i < inputs.length; i++) {"); sb.append("if (inputs[i].name.toLowerCase() === 'applyname') {applyname = inputs[i];}"); sb.append("else if (inputs[i].name.toLowerCase() === 'pccc_applyname') {pccc_applyname= inputs[i];}"); sb.append("}"); sb.append("if (pccc_applyname!= null) {str += pccc_applyname.value;}"); sb.append("if (applyname!= null) { str += ' , ' + applyname.value;}"); sb.append("window.JSInterface.processFormInputs(str);"); sb.append("return true;"); sb.append("};"); return sb.toString(); } @OnClick(R.id.iv_tools_left) public void onBack(View view) { finish(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) { mWebView.goBack();// 返回前一個頁面 return true; } return super.onKeyDown(keyCode, event); } class JavaScriptInterface { @JavascriptInterface public void processFormInputs(String html) { LogUtils.e("html-->" + html); } } }