bMon
bMon

Reputation: 962

Webview resource listener not catching loaded resources

I have a webview application that listens to clicks and compares them to predefined strings to check if I need to hook into my Java.

I started with the obvious:

shouldOverrideUrlLoading

and in there do something along the lines of:

if(url.contains(myhook)){
   //do what i need 
}

This is fine for when its dealing with user clicks in the webview. But now I'm at the point where I need to catch if a resource loads a url. So I found 'onLoadResource' and figured this is what I want - but I cannot get it working.

My general setup:

private String myhook = "http://domain.com/listener";
{ ... }
@Override
public void onLoadResource(WebView view, String url)
    {
    if(url.contains(myhook)){

        //do my stuff!!

        mWebView.loadUrl("http://domain.com/success.html");
    }
    else
    {
        super.onLoadResource(view, url);
    }           
}

My web code (index.html):

{...}
<a href="http://domain.com/processing.php" >sign up</a>
{...}

That calls my php processing page:

<?php
{...}
header('Location: http://domain.com/listener/?data=#data#');
?>

But my hook never gets invoked so success.html never gets loaded and my "do my stuff" never happens. It tries to send the request to http://domain.com/listener/?data=#data# which doesn't exist (I'm just using that to grab #data#).

One thing to note is that my "onLoadResource" is inside my private class TestWebViewClient extends WebViewClient { right before my @Override public boolean shouldOverrideUrlLoading - not sure if this is correct.

Any help or other methods would be appreciated.

Upvotes: 1

Views: 3551

Answers (1)

xandy
xandy

Reputation: 27421

the onLoadResource() will not trigger, neither do shouldOverrideUrlLoading() will trigger in this case, this is a bit disappointing but I found that in a WebView, all those requests within a html page is not triggered (like Images, CSS and so on). You have two options:

  1. Inject Javascript in that html that knows how to communicate with Android Java. http://developer.android.com/reference/android/webkit/WebSettings.html#setJavaScriptEnabled(boolean)
  2. Pre-process your html page and replace all those parts that request the resource you need with something you desired.

I once made a RSS reader which needs Caching images. I use the (2) approach and replace all img sources to local resource. It works but quite some heavy works though. At that time I just use Simple Regex to do the replacement but alternatively you can use library like HTMLTidy to help you.

Upvotes: 2

Related Questions