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

項目需要在遠程網(wǎng)頁里面調(diào)用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.
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容