how to get html content from a webview?

后端 未结 12 1556
鱼传尺愫
鱼传尺愫 2020-11-22 04:29

Which is the simplest method to get html code from a webview? I have tried several methods from stackoverflow and google, but can\'t find an exact method. Please mention an

相关标签:
12条回答
  • 2020-11-22 05:05

    Its Simple to implement Just need javasript methods in your html to get value of html content. As Above your code some changes to be need.

      public class htmldecoder extends Activity implements OnClickListener,TextWatcher
        {
        Button btsubmit; // this button in your xml file
        WebView wvbrowser;
        public void onCreate(Bundle savedInstanceState)
        {
                    super.onCreate(savedInstanceState);
                        setContentView(R.layout.htmldecoder);
    
    
    
            btsubmit=(Button)findViewById(R.id.btsubmit);
            btsubmit.setOnClickListener(this);
    
            wvbrowser=(WebView)findViewById(R.id.wvbrowser);
            wvbrowser.setWebViewClient(new HelloWebViewClient());
            wvbrowser.getSettings().setJavaScriptEnabled(true);
            wvbrowser.getSettings().setPluginsEnabled(true);
            wvbrowser.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
            MyJavaScriptInterface myinterface=new MyJavaScriptInterface();
            wvbrowser.addJavascriptInterface(myinterface,"interface");
            webView.loadUrl("file:///android_asset/simple.html");  //use one html file for //testing put your html file in assets. Make sure that you done JavaScript methods to get //values for html content in html file . 
       }
       public void onClick(View v)
    {
        if(btsubmit==v)
        {
    
            webView.loadUrl("javascript:showalert()");// call javascript method.  
            //wvbr
        }
    }
    
    final class MyJavaScriptInterface {
    
    
    
            MyJavaScriptInterface() {
    
            }
    
            public void sendValueFromHtml(String value) {
               System.out.println("Here is the value from html::"+value);
            }
    
        }
    
    }
    

    Your Javascript in html

     <script type="text/javascript">
        //<![CDATA[
        var n1;
        function callme(){
        n1=document.getElementById("FacadeAL").value;
        }
        function showalert(){
         window.interface.sendValueFromHtml(n1);// this method calling the method of interface which //you attached to html file in android. // & we called this showalert javasript method on //submmit buttton click of android. 
        }
        //]]>
        </script>
    

    & Make sure you calling callme like below in html

    <input name="FacadeAL" id="FacadeAL" type="text" size="5" onblur="callme()"/>
    Hope this will help you.

    0 讨论(0)
  • 2020-11-22 05:09

    Android will not let you do this for security concerns. An evil developer could very easily steal user-entered login information.

    Instead, you have to catch the text being displayed in the webview before it is displayed. If you don't want to set up a response handler (as per the other answers), I found this fix with some googling:

    URL url = new URL("https://stackoverflow.com/questions/1381617");
    URLConnection con = url.openConnection();
    Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
    Matcher m = p.matcher(con.getContentType());
    /* If Content-Type doesn't match this pre-conception, choose default and 
     * hope for the best. */
    String charset = m.matches() ? m.group(1) : "ISO-8859-1";
    Reader r = new InputStreamReader(con.getInputStream(), charset);
    StringBuilder buf = new StringBuilder();
    while (true) {
      int ch = r.read();
      if (ch < 0)
        break;
      buf.append((char) ch);
    }
    String str = buf.toString();
    

    This is a lot of code, and you should be able to copy/paster it, and at the end of it str will contain the same html drawn in the webview. This answer is from Simplest way to correctly load html from web page into a string in Java and it should work on Android as well. I have not tested this and did not write it myself, but it might help you out.

    Also, the URL this is pulling is hardcoded, so you'll have to change that.

    0 讨论(0)
  • 2020-11-22 05:09

    I suggest to try out some Reflection approach, if you have time to spend on the debugger (sorry but I didn't have).

    Starting from the loadUrl() method of the android.webkit.WebView class:

    http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.2_r1.1/android/webkit/WebView.java#WebView.loadUrl%28java.lang.String%2Cjava.util.Map%29

    You should arrive on the android.webkit.BrowserFrame that call the nativeLoadUrl() native method:

    http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.2_r1.1/android/webkit/BrowserFrame.java#BrowserFrame.nativeLoadUrl%28java.lang.String%2Cjava.util.Map%29

    The implementation of the native method should be here:

    http://gitorious.org/0xdroid/external_webkit/blobs/a538f34148bb04aa6ccfbb89dfd5fd784a4208b1/WebKit/android/jni/WebCoreFrameBridge.cpp

    Wish you good luck!

    0 讨论(0)
  • 2020-11-22 05:13

    For android 4.2, dont forget to add @JavascriptInterface to all javasscript functions

    0 讨论(0)
  • 2020-11-22 05:15

    above given methods are for if you have an web url ,but if you have an local html then you can have also html by this code

    AssetManager mgr = mContext.getAssets();
                 try {
    InputStream in = null;              
    if(condition)//you have a local html saved in assets
                                {
                                in = mgr.open(mFileName,AssetManager.ACCESS_BUFFER);
                               }
                                else if(condition)//you have an url
                                {
                                URL feedURL = new URL(sURL);
                      in = feedURL.openConnection().getInputStream();}
    
                                // here you will get your html
                     String sHTML = streamToString(in);
                     in.close();
    
                     //display this html in the browser or web view              
    
    
                 } catch (IOException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
                 }
            public static String streamToString(InputStream in) throws IOException {
                if(in == null) {
                    return "";
                }
    
                Writer writer = new StringWriter();
                char[] buffer = new char[1024];
    
                try {
                    Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
    
                    int n;
                    while ((n = reader.read(buffer)) != -1) {
                        writer.write(buffer, 0, n);
                    }
    
                } finally {
    
                }
    
                return writer.toString();
            }
    
    0 讨论(0)
  • 2020-11-22 05:16

    I would suggest instead of trying to extract the HTML from the WebView, you extract the HTML from the URL. By this, I mean using a third party library such as JSoup to traverse the HTML for you. The following code will get the HTML from a specific URL for you

    public static String getHtml(String url) throws ClientProtocolException, IOException {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpClient.execute(httpGet, localContext);
            String result = "";
    
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(
                    response.getEntity().getContent()
                )
            );
    
            String line = null;
            while ((line = reader.readLine()) != null){
                result += line + "\n";
            }
            return result;
        }
    
    0 讨论(0)
提交回复
热议问题