Relaxing Mime Type Checking In Android's Webview? Or Forcing Module Type For Regular Javascript?
Solution 1:
I am just restating the previous answer in an easier to read way (and with Java instead of Kotlin)
Not sure it matters, but it's best practice to use html 5 by adding
<!DOCTYPE html>
import androidx.webkit.WebViewAssetLoader;
as described in this other questionforce 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;
}
});
- 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?"