在按钮上单击从 WebView 文本区域获取内容 Android

On Button Click Get contents from a WebView textarea Android

我在 google 和 Whosebug 上进行了搜索,但找不到任何与 Android API 17 及更高版本相关的解决方案。

我喜欢在单击按钮时从 Web 视图中检索数据。

我喜欢实现类似于 ios 的东西:

myText.stringByEvaluatingJavaScriptFromString
    ("document.getElementById('chapter-description').value")

我的源代码是:

package com.xyz.webviewtest;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

public class MainActivity4 extends AppCompatActivity {
    TextView textView;

    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final WebView webview = (WebView) findViewById(R.id.webView);
        webview.getSettings().setJavaScriptEnabled(true);

        webview.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");

        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                webview.loadUrl("javascript:window.HtmlViewer.showHTML" +
                        "('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");

            }
        });
       // new MyJavaScriptInterface(this).showHTML("HtmlViewer");

        webview.loadUrl("http://www.xsoftech.com");
    }

    class MyJavaScriptInterface {

        private Context ctx;

        MyJavaScriptInterface(Context ctx) {
            this.ctx = ctx;
        }

        public void showHTML(String html) {
            new AlertDialog.Builder(ctx).setTitle("HTML").setMessage(html)
                    .setPositiveButton(android.R.string.ok, null).setCancelable(false).create().show();
        }

    }
}

http://developer.android.com/ 声明构造函数已弃用

This constructor was deprecated in API level 17. Private browsing is no longer supported directly via WebView and will be removed in a future release. Prefer using WebSettings, WebViewDatabase, CookieManager and WebStorage for fine-grained control of privacy data.

Webview 有文本区域,所以我可以在写完后写一些东西我希望能够在单击按钮时获取数据。实际上,我能够获取有关 webview 加载时间的数据,但无法获取有关在 webview 中的 textarea 上写入后单击按钮的数据。

我找到了一个可能的解决方案,但我无法在单击按钮时获得任何数据。

解决方法是:

    package example.xsoftech.sample;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;


public class Main2 extends Activity {
    WebView webview1;
    public static String data;
    Button button;
    String sUrl = "http://www.facebook.com/";

    // String sUrl = "http://www.xsoftech.com";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        button = (Button)findViewById(R.id.button);

         webview1 = (WebView)findViewById(R.id.myWebview);

         webview1.getSettings().setJavaScriptEnabled(true);
          webview1.addJavascriptInterface(new MyJavaScriptInterface(), "MYOBJECT");

        //FIXME I want to get value on button click but it's not working.So plz give me solution for work it?
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(Main2.this, "click is done: "+data, Toast.LENGTH_SHORT).show();
                data= "";
                webview1.loadUrl(sUrl);
            }
        });


        webview1.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.d("lifecyle", "shouldOverrideUrlLoading");

                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.d("lifecyle", "onpagefinished");
                StringBuilder sb = new StringBuilder();



                sb.append("document.getElementsByTagName('form')[0].onsubmit = function () {");
                sb.append("var objPWD, objAccount;var str = '';");
                sb.append("var inputs = document.getElementsByTagName('input');");
                sb.append("for (var i = 0; i < inputs.length; i++) {");
                sb.append("if (inputs[i].type.toLowerCase() === 'password') {objPWD = inputs[i];}");
                sb.append("else if (inputs[i].name.toLowerCase() === 'email') {objAccount = inputs[i];}");
                sb.append("}");
                sb.append("if (objAccount != null) {str += objAccount.value;}");
                sb.append("if (objPWD != null) { str += ' , ' + objPWD.value;}");
                sb.append("window.MYOBJECT.processHTML(str);");
                sb.append("return true;");
                sb.append("};");

                view.loadUrl("javascript:" + sb.toString());

            }

        });


        webview1.loadUrl(sUrl);

    }

    class MyJavaScriptInterface
    {
        @JavascriptInterface
        public void processHTML(String html)
        {
            data = html;
            AlertDialog.Builder builder = new AlertDialog.Builder(Main2.this);
            builder.setTitle("AlertDialog from app")
                    .setMessage(html)
                    .setPositiveButton(android.R.string.ok,
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // TODO Auto-generated method stub

                                }
                            })
                    .setCancelable(false).show();

        }
    }

}

感谢任何帮助。

  1. Enable javascript
  2. Add your own javascript
  3. 注册你自己的 webviewClient,覆盖 onPageFinished 插入一点 javascript
  4. 在javascript中获取tag的element.innerText,传给你的javascript接口

很高兴回答

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        button = (Button)findViewById(R.id.button);

        final WebView browser = (WebView)findViewById(R.id.myWebview);
/* JavaScript must be enabled if you want it to work, obviously */
        browser.getSettings().setJavaScriptEnabled(true);

/* Register a new JavaScript interface called HTMLOUT */
        browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");

/* WebViewClient must be set BEFORE calling loadUrl! */
        browser.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url)
            {
        // This call inject JavaScript into the page which just finished loading.
                browser.loadUrl("javascript:window.HTMLOUT.processHTML(document.getElementsByTagName('textarea')[0].innerHTML);");
            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                browser.loadUrl("javascript:window.HTMLOUT.processHTML(document.getElementById('chapter-description').value);");
            }
        });

/* load a web page */
        browser.loadUrl(sUrl);

    }