Not allowed to load local resource: file:///android_asset/xxx

项目需要在远程网页里面调用app中assets目录下的某个js文件,
开始这样写的

 <script src="file:///android_asset/test.js"></script>

结果运行提示:

[INFO:CONSOLE(25) ]Not allowed to load local resource: file:///android_asset/xxx

在百度搜了半天没人解决,无奈去stackoverflow

才找到有效的回答(亲测有效):

    
//A bit of an intrusive hack, but I worked around this issue by introducing a 
//"unique token" and implementing the WebViewClient with a 
//shouldInterceptRequest override.

//First, change the URL from file:///android/asset to a relative path with a 
//uniquely identifying token:

<script src="**injection**www/scripts.js"></script>
Then, override shouldInterceptRequest as follows:

// Injection token as specified in HTML source
private static final String INJECTION_TOKEN = "**injection**";

webView.setWebViewClient(new WebViewClient() {

    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
        WebResourceResponse response = super.shouldInterceptRequest(view, url);
        if(url != null && url.contains(INJECTION_TOKEN)) {
            String assetPath = url.substring(url.indexOf(INJECTION_TOKEN) + INJECTION_TOKEN.length(), url.length());
            try {
                response = new WebResourceResponse(
                        "application/javascript",
                        "UTF8",
                        getContext().getAssets().open(assetPath)
                );
            } catch (IOException e) {
                e.printStackTrace(); // Failed to load asset file
            }
        }
        return response;
    }
});
This is likely to degrade WebView performance slightly as we are calling the contains() on each resource which is attempted to be loaded, but it's the only workaround I've found to this issue.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容