android - Lollipop 中的 WebView 不会从资源中加载字体

标签 android html webview assets android-5.0-lollipop

我正在使用 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/

相关文章:

android - 更改整个 React Native App 的语言

android - 在 ViewPager 的多个选项卡中使用单个 fragment

android - 如何使用 Codename One 测试 Android native 代码 fragment ?

android - 如何确保我的应用程序仅适用于 Android Market 上的手机?

javascript - 隐藏 div,以防一个内部 div 为空 Jquery 或 CSS3

html - 打开插件时的 Tinymce 插件图像不会换行到父 div 的宽度

html - 如何使垂直滚动条更薄并摆脱右下角的空白空间?

webview - 为什么 initState 在 WebView 上的 url 更改后不起作用?

android - 在 webview 而不是默认浏览器中打开链接

android - 来自 URL 的 CSS 在 JSoup 中不起作用