Determine element of url from webview shouldOverRideUrlLoading
I am displaying a html in a custom activity with a webview. I am overriding
public boolean shouldOverrideUrlLoading(WebView view, String url) {
to intercept certain urls. Now I would like to be able to figure out some more details about the html around that url.
In my case I would like to get the html element that contains the url. E.g. if the url comes from
<a href="http://stackoverflow.com/users/136445/manfred-moser">Manfred Moser</a>
I would like to be able to somehow retrieve the value "Manfred Moser" from within the anchor tag. Is there a way to do that. I found that you do not have access to the DOM from Java.
One way I can th开发者_StackOverflowink of would be to download the page separately and parse it all before even loading it in webview. However that is an ugly hack at best. Is there a better way?
There is a dirty hack:
Bind some Java object so that it can be called from Javascript with WebView:
addJavascriptInterface(javaObjectExposed, "JSname")
Force execute javascript within an existing page by
WebView.loadUrl("javascript:window.JSname.passData("some data");");
Described here: http://lexandera.com/2009/01/extracting-html-from-a-webview/
Note: this is a security risk - any JS code in this web page could access/call your binded Java object. Best to pass some one-time cookies to loadUrl() and pass them back your Java object to check that it's your code making the call.
In addition to @Peter Knego's approach, there is the inverse:
Use
addJavascriptInterface()
, per his step #1For your link, use an
onClick
attribute on your<a>
tag to call out some method on the Java object from step #1, where the Java object turns around and loads the URL into theWebView
, and supplies whatever sort of identifying information you want.
Suffice it to say, there's no way to get the information you want from shouldOverrideUrlLoading()
.
精彩评论