【问题标题】:WebView in Lollipop doesn't load fonts from assetsLollipop 中的 WebView 不会从资产中加载字体
【发布时间】:2015-02-02 12:26:05
【问题描述】:

我正在使用 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控制台看到如下信息:

来自“asset://”的字体已被阻止加载 跨域资源共享策略:没有“Access-Control-Allow-Origin” 请求的资源上存在标头。原点“空”是 因此不允许访问。

如何在 Android 5.0 上从资产加载字体?

【问题讨论】:

    标签: android html webview assets android-5.0-lollipop


    【解决方案1】:

    您需要使用新的WebResourceResponse 构造函数来设置HTTP 标头以与截获的请求一起传递。

    由于新的构造函数仅在 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 进行构建。

    【讨论】:

      猜你喜欢
      • 2017-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-10
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多