2

My goal is to set a String equals to a text inside an HTML page loaded into my webview. This is the HTML code:

<!DOCTYPE html>
<html>
<body>
<span class="txtTitle" style="color:#f93f3f; font-size:17px;">Hello World</span>
</body>
</html>

What I would like to know is to pass the "Hello World" in a String.

What I have already done is this:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    WebView view = (WebView) findViewById(R.id.webView);
    WebSettings asd = view.getSettings();
    String url = "http://example.net";
   asd.setJavaScriptEnabled(true);
   view.loadUrl(url);
    view.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
        String text;    
        text = view.loadUrl("javascript:document.getElementsByClassName('txtTitle')[0].innerHTML");
        }
    });
    }

But of course it gives me an error saying that the loadValue() can't be a String. Any Advice??

1 Answer 1

1

You can bind javascript to android code in order to return a string.

Read more: http://developer.android.com/guide/webapps/webview.html#BindingJavaScript

Here's a simple example to accomplish your goals.

public class MainActivity extends Activity {

WebView view;
JSInterface api;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    view = (WebView) findViewById(R.id.webView);
    api = new JSInterface();
    WebSettings asd = view.getSettings();

    asd.setJavaScriptEnabled(true);
    view.addJavascriptInterface(api, "api");

    String url = "file:///android_asset/index.html";
    view.loadUrl(url);
    view.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        public void onPageFinished(WebView view, String url) {
            view.loadUrl("javascript:api.getString(document.getElementsByClassName('txtTitle')[0].innerHTML)");
        }
    });
}

private class JSInterface {

    @JavascriptInterface
    public void getString(String str) {
        Log.d("STRING", str);
    }

}
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very very much for the answer man. Just last question If I would try to print the String that I got what should I do.. Which is the variable i got from this code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.