Force Android WebView Offline

We want to use the standard Android WebView as a sandbox to run local HTML / JS applications. The basic security requirement is to completely disable WebView and allow only certain javascript interfaces to be called. These interfaces are passed to the javascript runtime using the WebView.addJavascriptInterface () method.

The Android application itself has permission to access the network (android.permission.INTERNET).

I can disable normal http / https requests, but completely blocked WebSocket requests . They seem to be handled differently than regular http requests.

One alternative is to rewrite the JavaScript WebSocket method. But this gives me a bad feeling about it, since it contradicts the concept of the sandbox. It is also possible to use delete to restore the original function pointer.

Another alternative would be to link our own custom WebView (e.g. Crosswalk-Project) with our application, but we would like to avoid this, as compilation and updates are quite time-consuming.

I tried the following public WebView interfaces, but none of them block WebSocket calls:

  • webSettings.setBlockNetworkLoads (true);
  • webSettings.setCacheMode (WebSettings.LOAD_CACHE_ONLY);
  • webView.setNetworkAvailable (false);
  • WebViewClient.shouldOverrideUrlLoading () (callback)
  • WebViewClient.shouldInterceptRequest() ( , )
  • WebChromeClient.onPermissionRequest()

Android 4.4.4 (19) Android 5/5.1 (21/22).

JavaScript, :

ws = new WebSocket("wss://echo.websocket.org");

ws.onmessage = function(event) {
  console.log("received: " + event.data);
};

ws.onclose = function() {
  console.log("External Socket closed");
};

ws.onopen = function() {
  console.log("Connected to external ws");
  ws.send("Hello from " + navigator.userAgent);
};

, ?

+5
2

, WebSockets WebView. JavaScript . , WebSocket , , , window, . , WebSocket WebView.addJavascriptInterface.

, HTML- WebView, Javascript .

, WebView WebView - Binder IPC.

WebView , , .

0

, , -:

<meta http-equiv="Content-Security-Policy" content="connect-src 'none';"/>

, , websocket echo.websocket.org CSP .

ShouldInterceptRequest; :

public override WebResourceResponse ShouldInterceptRequest(WebView view, IWebResourceRequest request)
{
    using (var stream = view.Context.Assets.Open("test.html"))
    {
        var resp = new WebResourceResponse("text/html", "UTF-8", stream);
        resp.ResponseHeaders = new Dictionary<string, string>();
        resp.ResponseHeaders.Add("Content-Security-Policy", "connect-src 'none';");
        return resp;
    }
}

, file:///android_asset/... file:///android_res/... , file:///... .

, Android 8.0. , Chrome CSP 2013 , , Android.


CSP, , . , file://, - :

default-src 'self' 'unsafe-inline' 'unsafe-eval' data: blob: filesystem:;
0

All Articles