JavaScript (stored inside assets) not working inside WebView in ICS (Ice Cream Sandwich)

一世执手 提交于 2019-12-21 19:52:39

问题


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.



来源:https://stackoverflow.com/questions/18799880/javascript-stored-inside-assets-not-working-inside-webview-in-ics-ice-cream-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!