Skip to content Skip to sidebar Skip to footer

Relaxing Mime Type Checking In Android's Webview? Or Forcing Module Type For Regular Javascript?

I am developing and app in Android which has a piece written in javascript and python using Transcrypt (it'd almost be the same as saying that I am developing that part straight in

Solution 1:

I am just restating the previous answer in an easier to read way (and with Java instead of Kotlin)

  1. Not sure it matters, but it's best practice to use html 5 by adding <!DOCTYPE html>

  2. import androidx.webkit.WebViewAssetLoader; as described in this other question

  3. force the correct MIME type with something like

        mWebView.setWebViewClient(newWebViewClient() {
            @Overridepublic WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                WebResourceResponseintercepted= assetLoader.shouldInterceptRequest(request.getUrl());
                if (request.getUrl().toString().endsWith("js")) {
                        if (intercepted != null) {
                            intercepted.setMimeType("text/javascript");
                        }
                }
                return intercepted;
            }
        });
  1. load the HTML with something like
WebSettingswebSettings= mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mWebView.loadUrl("https://appassets.androidplatform.net/assets/AndroidWebView.html");

Note the HTTPS (not file) protocol, and the absence of AllowFileAccessFromFileURLs

Solution 2:

Some things you could try.

1. Make sure it is html 5 by adding <!DOCTYPE html> to your index.html

2. Instead of loading the file directly from the system using file://... you can use the WebViewAssetLoader this will return the mimetype https://developer.android.com/reference/kotlin/androidx/webkit/WebViewAssetLoader

3. If that does not work inside the webViewClient you could intercept the request and add the text/javascript mimetype manually:

val webViewAssetLoader = WebViewAssetLoader.Builder()
        .addPathHandler("/assets/", WebViewAssetLoader.AssetsPathHandler(context!!))
        .build()

val webViewClient = object : WebViewClient() {

    overridefunshouldInterceptRequest(view: WebView?, request: WebResourceRequest): WebResourceResponse? {
        val interceptedWebRequest = webViewAssetLoader.shouldInterceptRequest(request.url)
        interceptedWebRequest?.let {
            if (request.url.toString().endsWith("js", true)) {
                it.mimeType = "text/javascript"
            }
        }
        return interceptedWebRequest
    }
}

Post a Comment for "Relaxing Mime Type Checking In Android's Webview? Or Forcing Module Type For Regular Javascript?"