Android Webview: disable CORS

Does Android support native applications to disable CORS security policies for http: // requests (not local / files)?

In my native application, the webview shows the remote html via http: // and not the local / file system. This is similar to a CORS restriction, as in web browsers.

Worakround: The native-js bridge for ajax requests for cross-domains that don't have Access-Control-Allow-Origin: * is my quick'n'dirt solution. (A jsonp or server-side proxy is not an option, because the cookie + ip of the client is checked by the web service.)

Can I disable this policy for inapp web views?

Please let me know if there is a simple flag allowing js to bypass this restriction, which limits the "native" webview application.

+6
source share
2 answers

AFAIK is not possible, and believe me, I have tried many ways.

The best you can do is override resource loading. See Intercepting and Overriding HTTP Requests from WebView

+7
source

Now it is possible with Android API level 21. You can create an OPTIONS response as follows:

 public class OptionsAllowResponse { static final SimpleDateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy kk:mm:ss", Locale.US); @TargetApi(21) static WebResourceResponse build() { Date date = new Date(); final String dateString = formatter.format(date); Map<String, String> headers = new HashMap<String, String>() {{ put("Connection", "close"); put("Content-Type", "text/plain"); put("Date", dateString + " GMT"); put("Access-Control-Allow-Origin", /* your domain here */); put("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS"); put("Access-Control-Max-Age", "600"); put("Access-Control-Allow-Credentials", "true"); put("Access-Control-Allow-Headers", "accept, authorization, Content-Type"); put("Via", "1.1 vegur"); }}; return new WebResourceResponse("text/plain", "UTF-8", 200, "OK", headers, null); } } 

and then call it from your WebViewClient implementation as follows:

  @Override @TargetApi(21) public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { if (request.getMethod().equalsIgnoreCase("OPTIONS")) { return OptionsAllowResponse.build(); } return null; } 

This only works from API level 21, as the OPTIONS response requires checking the requested HTTP method from WebResourceRequest, which is only available with API 21.

+2
source

Source: https://habr.com/ru/post/947977/


All Articles