partiz
partiz

Reputation: 1216

Access Meta Data from android WebView

How to access Meta Data of a HTML page loaded into a WebView in Android?

I search for hours stackoverflow.com and google and I coudn't find any answer.

I only could get url and title by this code:

webView.getTitle();
webView.getUrl();

Dose is it imposible and webview not support it?

Upvotes: 1

Views: 5062

Answers (3)

wang shi
wang shi

Reputation: 39

You can solve the problem by this easy way:

private class JsInterface {
    @JavascriptInterface
    @SuppressWarnings("unused")
    public void processHTML(String content) {
    //handle content
    }
}


mWebView.addJavascriptInterface(new JsInterface(), "CC_FUND");

mWebView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url) {
        mWebView.loadUrl("javascript:window.CC_FUND.processHTML( (function (){var metas = document.getElementsByTagName('meta'); \n" +
                "\n" +
                "   for (var i=0; i<metas.length; i++) { \n" +
                "      if (metas[i].getAttribute(\"name\") == \"description\") { \n" +
                "         return metas[i].getAttribute(\"content\"); \n" +
                "      } \n" +
                "   } \n" +
                "\n" +
                "    return \"\";})() );");
        super.onPageFinished(view, url);
    }
}

Upvotes: 1

koder
koder

Reputation: 554

If its your own web page then you can pass the meta description or any text to your app using the below code:

public class WebAppInterface {

    @JavascriptInterface
    public void setDesc(String desc) {
        mDescription = desc;
    }
}

Then add JS interface to WebView:

webView.addJavascriptInterface(new WebAppInterface(), "Android");

Finally, add the following code in your webpage:

<script type="text/javascript">    
    Android.setDesc("Your meta tag desc here");
</script>

Read more at https://developer.android.com/guide/webapps/webview.html

Upvotes: 0

kris larson
kris larson

Reputation: 30985

Don't open the URL in the WebView.

First. open an HttpURLConnection to the URL. Read the output from the server and you can scan through the server response to find your meta data.

As you are reading the server output, write the data into a buffer, then use loadData instead of loadUrl to display the buffered data in the WebView

Upvotes: 3

Related Questions