JavaScript (stored inside assets) not working insi

2019-04-12 01:29发布

问题:

Similar Problem : JavaScript doesn't work on ICS

I'm working on an Android app that displays some code samples to the user. So, I'm using google-code-prettify in a WebView for syntax highlighting. But, the problem is, the js does not work on ICS (Ice Cream Sandwich) alone. It works perfectly on all other Android versions (2.2+) except 4.0.x. This is the code that I'm using.

WebView webView = (WebView) findViewById(R.id.webViewSample);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
webView.loadUrl("file:///android_asset/code_snippets/sample_java.html");

The only error-like message that I get from logcat is UNKNOWN CHROMIUM ERROR: -6

Any help would be great. Thanks in advance.

回答1:

Didn't find any proper solution.. So, I ended up following MoshErsan's suggestion as mentioned here:

This is what I did:

WebView webView = (WebView) findViewById(R.id.webView);       
webView.setWebViewClient(new WebViewClient(){
    @TargetApi(11)
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
        Log.d("shouldInterceptRequest", url);
        InputStream stream = inputStreamForAndroidResource(url);
        if (stream != null) {
            return new WebResourceResponse("text/javascript", "utf-8", stream);
        }
        return super.shouldInterceptRequest(view, url);
    }
    private InputStream inputStreamForAndroidResource(String url) {
        final String ANDROID_ASSET = "file:///android_asset/";
        if (url.contains(ANDROID_ASSET)) {
            url = url.replaceFirst(ANDROID_ASSET, "");
            try {
                AssetManager assets = getAssets();
                Uri uri = Uri.parse(url);
                return assets.open(uri.getPath(), AssetManager.ACCESS_STREAMING);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }           
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///android_asset/code_snippets/sample_java.html");

Don't know what the actual problem is. But, this hack works.