2

How can i load resources dynamically from an android webview using onLoadResource() callback from a webviewClient?

Below is the code i have written so far. when i get new resources, it loads for example, the whole page of one single imagine instead of updating and displaying the image on the same original url of the webpage.

If a webpage has 5 images and text, my current code will load 5 pages each time onLoadResource tries to load an image.

what i want it to do is to load the images in the same page and any other resources as well such as JS, jquery's etc.

@Override
    public void onLoadResource(WebView view, String url) {
   addRequestToProxy(url);

}


public void addRequestToProxy(String url){
//pass url to proxy and wait for respoonse
String response;
//handle response

if(mime-type == IMAGE){
String urlStr = "http://example.com/my.jpg";
        String pageData = "<img src=\"data:" + contentResponse.getMimeType()
                + ";base64," + contentResponse.getContent() + "\" />";

        mWebView.loadDataWithBaseURL(urlStr, pageData, "text/html", null,
                urlStr);
}else{

mWebView.loadDataWithBaseURL(null, response, "text/html", null,
                        null);
}
Jono
  • 17,341
  • 48
  • 135
  • 217

1 Answers1

1

Instead of overriding onLoadResource() it's better to do it this way - shouldInterceptRequest()

webview shouldInterceptRequest example

Community
  • 1
  • 1
cyberflohr
  • 789
  • 5
  • 10
  • Not applicable for older Android OS's – Jono Jun 24 '13 at 11:14
  • The example also contains information what to do for Android 2.x systems. --- If you want to do something similar for Android 2.x, you might want to try using the earlier mentioned shouldOverrideUrlLoading(WebView view, String url)-- – cyberflohr Jun 24 '13 at 13:19
  • A complete other approach is setting a proxy for the webview. Look at the following [Gist example](https://gist.github.com/madeye/2297083) – cyberflohr Jun 24 '13 at 13:25
  • shouldOverideUrlLoading only gets invoked when u load a new page, not its resources – Jono Jun 24 '13 at 14:37
  • OK you are right - shouldOverideUrlLoading() is not applicable What do you think about the proxy solution (see above)? – cyberflohr Jun 24 '13 at 14:52
  • 1
    The proxy solution just uses a custom httpClient to make the requests for u. it doesnt specify how to load the actual webpage's resources. the proxy solution is not ideal because you can do the exact same thing on shouldOverideUrlLoading by moving the httpClient code there – Jono Jun 24 '13 at 15:02
  • 1
    The big problem in your case is the support for android < 11 Another solution which works also in android < 11 is a content provider. you can load the resource within the html page over this content provider. i.e. to load all subsequent resources over this provider. – cyberflohr Jun 24 '13 at 15:16