Issue
I have tried for a long time now to find a way to get the HTML content from a Web View which i load up in an android application. I have found several guides stating that i need to use a javascript interface and to some extent i have made that work. The problem now is that i can't get the final step done where i actually get a String of the HTML which i can manipulate with. I need a String where i can play with the html in the java code after i have retrieved it from the Web View. Here is my code so far:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//login button
Button loginButton = (Button) findViewById(R.id.loginButton);
final WebView webview = (WebView)(findViewById(R.id.webview));
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Call private method
webview.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
/* This call inject JavaScript into the page which just finished loading. */
webview.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('body')[0].innerHTML+'</head>');");
webview.setVisibility(View.INVISIBLE);
}
});
webview.setVisibility(View.VISIBLE);
MyJavaScriptInterface JSInterface = new MyJavaScriptInterface();
webview.getSettings().setJavaScriptEnabled(true);
webview.postUrl(url, SAMLreq.getBytes());
webview.addJavascriptInterface(JSInterface, "HTMLOUT");
//The html from the webview should be stored here
String htmlFromWebView = JSInterface.getTheHTMLToGo();
class MyJavaScriptInterface {
private String theHTMLToGo = null;
public String getTheHTMLToGo() {
return theHTMLToGo;
}
public void setTheHTMLToGo(String theHTMLToGo) {
this.theHTMLToGo = theHTMLToGo;
}
@SuppressWarnings("unused")
@JavascriptInterface
public void processHTML(String html) {
theHTMLToGo = html
}
}
}
I can see when i debug that the 'html' String in the javascript method called 'processHTML' actually contains the right value, but i still can't figure out how to get it out from there.
Solution
The solution was right in front of me the whole time. As it has also been commented on my post on this question: I am basically doing the right thing. My problem is that i call the method getTheHTMLToGo()too soon. I moved some code into the processHTML(String html) and made sure that the flow completed before i went on. I did this by calling the next thing i needed to do from within the processHTML(String html) method.
Answered By - Rasmus Pommer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.