Lollipop中的WebView不会从素材资源加载字体

 我是曰照人_692 发布于 2022-12-07 18:07

我正在使用WebView渲染一些html内容。在我的CSS中,我有以下代码:

@font-face {
  font-family: CharterC;
  font-style: normal;
  font-weight: normal;
  src: url("asset://fonts/CharterC.otf");
}

我的代码如下WebViewClient

    @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上从资产加载字体?

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进行构建。

    2022-12-11 02:58 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有