android webview obtains html code and obtains value instance according to id
- 2021-11-30 01:26:07
- OfStack
1 Preface
Recently do a project, need webview to get the content of input in the web page, to sort out the knowledge under 1, do a record, also hope to help everyone.
2 Get html content
2.1 Initialize webview
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new InJavaScriptLocalObj(), "java_obj");
/**
* Attention, @JavascriptInterface The annotation for the method is 1 It must be added,
* Many students have no effect because they didn't add it
*/
final class InJavaScriptLocalObj {
@JavascriptInterface
public void getSource(String html) {
Log.d("html=", html);
}
}
2.2 Get the html code
view.loadUrl("javascript:window.java_obj.getSource('<head>'+" +
"document.getElementsByTagName('html')[0].innerHTML+'</head>');");
When this sentence is executed, the getSource method in InJavaScriptLocalObj will be called back.
3 Get value from id
There may be a requirement to get the text box input in android after you have entered the text box in a Web page. So this text box needs to set an id, and we use the javascript code to get value. The code is as follows:
3.1 Initialize webview
The code of this 1 block is the same as that above
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new InJavaScriptLocalObj(), "local_obj");
public final class InJavaScriptLocalObj {
private String value = "";
public String getValue(){
return this.value;
}
@JavascriptInterface
public void getValueById(String value) {
Log.d("HTML", value);
this.value = value;
}
}
3.2 Obtain value from id
detail_web.loadUrl("javascript:window.local_obj.getValueById(document.getElementById('acount_comment').value);");
4 End