有點侵入性的黑客,但我通過引入一個「獨特的令牌」並執行WebViewClient
和覆蓋shouldInterceptRequest
工作解決此問題。
首先,改變從file:///android/asset
URL以相對路徑具有唯一地標識令牌:
<script src="**injection**www/scripts.js"></script>
然後,重寫shouldInterceptRequest
如下:
// 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;
}
});
這可能降低web視圖性能稍微,因爲我們正在調用每個試圖加載的資源上的,但這是我發現這個問題的唯一解決方法。
你是如何加載初始頁面?它來自服務器還是APK中的HTML文件? –
你好@dumazy!你有沒有找到解決辦法? – rahulritesh
@rahulritesh不是真的,它與shouldInterceptRequest有關,但我沒有找到正確的解決方案,所以我決定採取另一種方法... – dumazy