开发者

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:

  1. Bind some Java object so that it can be called from Javascript with WebView:

    addJavascriptInterface(javaObjectExposed, "JSname")
    
  2. 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:

  1. Use addJavascriptInterface(), per his step #1

  2. For 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 the WebView, 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().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜