Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Intercept AJAX call from WebView

I want a HTML/javascript application, running in a WebView to make AJAX calls that are handled by the Java code.
Ideal would be to just intercept the call (easy, just use shouldOverrideUrlLoading()) and 'return' some data.
However, I don't find a way to 'return' a response to the WebView, other than calling a javascript function using loadUrl().
This will not work for me, as the HTML/javascript app is a drop-in application which I don't control. As far as the HTML/javascript app concerns, it just does an AJAX call and receives some data back.

Any thoughts on this?

like image 667
Erik Avatar asked Oct 15 '10 11:10

Erik


1 Answers

Good news everyone: With API level 11, they put in the shouldInterceptRequest method into the WebViewClient class. It also fires on requests the application inside the WebView triggers. You can override it as follows:

@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url)
{
    if (magicallyMatch(url))
        return new WebResourceResponse("application/json", "utf-8", magicallyGetSomeInputStream());

    return null;
}

From the Android Reference:

public WebResourceResponse shouldInterceptRequest (WebView view, String url)

Since: API Level 11

Notify the host application of a resource request and allow the application to return the data. If the return value is null, the WebView will continue to load the resource as usual. Otherwise, the return response and data will be used. NOTE: This method is called by the network thread so clients should exercise caution when accessing private data.

Parameters

view The WebView that is requesting the resource.

url The raw url of the resource.

Returns

A WebResourceResponse containing the response information or null if the WebView should load the resource itself.

Also check WebResourceResponse.

Hope this helps.

like image 74
Nappy Avatar answered Sep 21 '22 10:09

Nappy