Reputation: 898
I've made an WebView application with javascript and user-prompt (dialog outside website, before webview loads) which I use to log in that website. Now I want to get some informations using jsoup, but problem is that jsoup gets informations from non-logged in homepage. For example, if I'm not logged in at website homepage does not have informations like Username, Messages etc. I want to get these informations using jsoup, but I can't since jsoup isn't actually reading same page as it's in webview. Is there any way I can somehow "connect" jsoup and webview so jsoup read pages as they are inside WebView? I need this to make android notifications about new messages...
Thanks in advance!
Upvotes: 0
Views: 2560
Reputation: 5876
You can execute javascript to pass the HTML content that was loaded back to the Activity that contains it by registering a JavascriptInterface
You can create the interface in your Activity as a private inner class:
private class MyJavaScriptInterface {
@JavascriptInterface
public void handleHtml(String html) {
// Use jsoup on this String here to search for your content.
Document doc = Jsoup.parse(html);
// Now you can, for example, retrieve a div with id="username" here
Element usernameDiv = doc.select("#username").first();
}
}
Then, attach this to your WebView:
webview.addJavascriptInterface(new MyJavaScriptInterface(), "HtmlHandler");
Finally, add a WebViewClient
that will call this javascript method every time the page loading completes. You will have to determine when the user is logged in based on the content of the page at that time:
webview.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
webview.loadUrl("javascript:window.HtmlHandler.handleHtml" +
"('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
}
});
Upvotes: 3