我正在使用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上从资产加载字体?
您需要使用新的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进行构建。