我正在使用 WebView
来呈现一些 html 内容。在我的 CSS 中,我有以下代码:
@font-face {
font-family: CharterC;
font-style: normal;
font-weight: normal;
src: url("asset://fonts/CharterC.otf");
}
我的 WebViewClient
中有以下 Java 代码:
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
if (url.startsWith(ASSETS_SCHEME)) {
String asset = url.substring(ASSETS_SCHEME.length());
if (asset.endsWith(".js")) {
try {
return new WebResourceResponse("text/javascript", "utf-8", context.getAssets().open(asset));
} catch (Exception e) {
e.printStackTrace();
}
} else if (asset.endsWith(".ttf") || asset.endsWith(".otf")) {
try {
return new WebResourceResponse("font/" + MimeTypeMap.getFileExtensionFromUrl(asset), "utf-8", context.getAssets().open(asset)); // this will produce MimeType like: font/ttf
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
这段代码在 Android 4.1–4.4 中运行得很好,但在 Android 5.0 中,这段代码加载了 js,但无法加载字体,并且我在 webkit 控制台中看到以下消息:
Font from origin 'asset://' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
如何在 Android 5.0 上从资源加载字体?
最佳答案
您需要使用新的 WebResourceResponse构造函数设置 HTTP header 以与拦截的请求一起传递。
由于新的构造函数仅在 Lollipop 中引入,因此请务必在运行时检查 SDK 版本。
InputStream inputStream = context.getAssets().open("fonts/myfontasset.ttf");
WebResourceResponse response = null;
String encoding= "UTF-8";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
int statusCode = 200;
String reasonPhase = "OK";
Map<String, String> responseHeaders = new HashMap<String, String>();
responseHeaders.put("Access-Control-Allow-Origin","*");
response = new WebResourceResponse("font/ttf", encoding, statusCode, reasonPhase, responseHeaders, inputStream);
} else {
response = new WebResourceResponse("font/ttf", encoding, inputStream);
}
注意:您必须至少针对 SDK 级别 21 进行构建。
关于android - Lollipop 中的 WebView 不会从资源中加载字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27297168/