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

北战南征 提交于 2019-12-04 13:06:48
niranjan94

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.

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