WIllJBD
WIllJBD

Reputation: 6164

how to get text from a webview

It seems so simple yet is becoming nearly impossible. There is text being displayed in my WebView and I need to get it.

I have tried all sorts of things.

webview.loadUrl("javascript:window.HTMLOUT.showHTML(document.innerText);");
webview.loadUrl("javascript:window.HTMLOUT.showHTML(document.documentElement.innerText);");

webview.loadUrl("javascript:window.HTMLOUT.showHTML(document.getElementsByTagName('auth')[0].innerHTML);");

webview.loadUrl("javascript:window.HTMLOUT.showHTML(document.getElementsByTagName('body')[0].innerText);");

webview.loadUrl("javascript:window.HTMLOUT.showHTML(document.getElementsByTagName('html')[0].innerText);");

and tons of other stuff. I get undefined for these two calls.

It always tries to return as some random xml.

class MyJavaScriptInterface   
{  
    @SuppressWarnings("unused")  
    public void showHTML(String html)  
    {  
        Log.d("SHOWING", html);

        new AlertDialog.Builder(myApp)  
            .setTitle("HTML")  
            .setMessage(html)  
            .setPositiveButton(android.R.string.ok, null)  
            .setCancelable(false)  
            .create()  
            .show();  
    }
    public void showHTML(Object html)  
    {
        Log.d("Some random object", "Some random object");
    }
    public void showHTML(XML html)  
    {
        Log.d("Some random XML", "Some random XML");
    }  
}  

thats what it looks like.

any help?

Upvotes: 0

Views: 5247

Answers (1)

JP_
JP_

Reputation: 1666

Here is an example of sending text from your webpage to your android device. It creates a 'toast' popup message on the android.

Add this to your webview:

myWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");

Add this class to your project:

 public class JavaScriptInterface {
    Context mContext;

    JavaScriptInterface(Context c) {
        mContext = c;
    }

    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
}

Send information from your website to your android with javascript like so:

    <script type="text/javascript">
           Android.showToast("This is a message");
    </script>

Upvotes: 2

Related Questions