Requests in AJAX works in WebView?

5

I have the following WebView :

WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setBuiltInZoomControls(true);
myWebView.loadUrl('http://192.168.0.4:8080/map/index.html?value_id=666');

Inside index.html has a Google map, which is requested through the Google Maps API, which contains some AJAX requests ( GET , POST , a local server) looking for some markers in the database . In the browser works normally, however within the application does not work. My suspicion is that these requests are not working because the markers are not appearing on the map. Here came the doubt:

  • Does AJAX request work in Webview? If so, what did I fail to set in WebView to work correctly? If not, is there a viable alternative to circumvent it?

See the tests

In browser :

Noapp:

    
asked by anonymous 23.05.2017 / 17:11

1 answer

2

The problem you should be having is with , you can not disable security in webView to avoid these problems, if you have access to the API then you should add the header:

Access-Control-Allow-Origin: *

If you do not have access to the API backend codes then what you can do is create a kind of proxy to be able to rewrite the headers

So I think as per this SOen answer you can do something similar:

webView.setWebViewClient(new WebViewClient() {

    ...

    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        final String method = request.getMethod();
        final String url = request.getUrl().toString();

        Log.d(TAG, "processRequest: " + url + " method " + method);

        String ext = MimeTypeMap.getFileExtensionFromUrl(url);
        String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);

        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestMethod(method);
            conn.setDoInput(true);
            conn.setUseCaches(false);

            Map<String, String> responseHeaders = convertResponseHeaders(conn.getHeaderFields());

            //Permite o CORS
            responseHeaders.put("Access-Control-Allow-Origin", "*");

            //Permite ajustar o content-type nas requisições ajax
            responseHeaders.put("Access-Control-Allow-Headers: Content-Type");

            return new WebResourceResponse(
                mime,
                conn.getContentEncoding(),
                conn.getResponseCode(),
                conn.getResponseMessage(),
                responseHeaders,
                conn.getInputStream()
            );

        } catch (Exception e) {
            Log.e(TAG, "shouldInterceptRequest: " + e);
        }

        return null;
    }
}
  

I have not tested yet but the answer is to use even shouldInterceptRequest if you do not have access to the API servers-side

    
23.05.2017 / 18:14