有点侵入性的黑客攻击,但我通过引入“唯一令牌”并WebViewClient
使用shouldInterceptRequest
覆盖来解决这个问题。
首先,将 URL 从 更改为file:///android/asset
具有唯一标识令牌的相对路径:
<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;
}
});
这可能会稍微降低 WebView 的性能,因为我们在contains()
尝试加载的每个资源上调用 ,但这是我发现的唯一解决此问题的方法。