Reputation: 733
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??
Upvotes: 2
Views: 1325
Reputation: 5213
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);
}
}
}
Upvotes: 1