WebView优化

来源:互联网 发布:数据库的规范化设计 编辑:程序博客网 时间:2024/05/14 18:35

Html直接调用Android的本地资源

需要解决的问题

  在Html中直接通过file:///android_asset/www/licai/lib/jquery-1.11.1.min.js 加载js文件,浏览器出于安全的原因不容许访问本地资源会抛出如下的错误:Not allowed to load local resource: file:///android_asset/www/licai/lib/jquery-1.11.1.min.js 找到的解决方案:
1. 在chrome浏览器中:
  使用控件解决:安装Chrome插件是 LocalLinks.安装的地址是: https://chrome.google.com/webstore/detail/locallinks/jllpkdkcdjndhggodimiphkghogcpida
2. 在WebView中,我们重写webview加载文件方式,shouldInterceptRequest 使用**PingAnNativeFile** 当做tonkenId使用
Html代码:
<script type="text/javascript" src="**PingAnNativeFile**www/licai/lib/jquery-1.11.1.min.js"></script>
java代码:

// Injection token as specified in HTML source                    private static final String INJECTION_TOKEN = "**PingAnNativeFile**www/licai";    @TargetApi(Build.VERSION_CODES.HONEYCOMB)    @Override    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {        WebResourceResponse response = super.shouldInterceptRequest(view, url);        if(url != null && url.contains(INJECTION_TOKEN)) {            String assetPath ="www/licai"+url.substring(url.indexOf(INJECTION_TOKEN) + INJECTION_TOKEN.length(), url.length());            Log.i("assetPath",assetPath);            try {                response = new WebResourceResponse(                        "application/javascript",                        "UTF8",                        getResources().getAssets().open(assetPath)                );            } catch (Exception e) {                e.printStackTrace(); // Failed to load asset file            }        }        return response;    }

因为WebResourceResponse 只支持API11以上的版本,所以要加上 @TargetApi(Build.VERSION_CODES.HONEYCOMB)

0 0
原创粉丝点击