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?
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
WebViewwill 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
viewTheWebViewthat is requesting the resource.
urlThe raw url of the resource.Returns
A
WebResourceResponsecontaining the response information or null if theWebViewshould load the resource itself.
Also check WebResourceResponse.
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With