javascript - 获取浏览器中渲染文本的确切字体,可能使用浏览器扩展

标签 javascript google-chrome firefox fonts browser-extension

<分区>

我知道您可以通过 window.getComputedStyle() 获取 font-family 值,但这并不总是浏览器用来呈现的字体。例如,如果给定文本包含字体系列不包含的(多语言)文本,则浏览器会使用系统字体部分呈现文本。

如果您查看 Chrome 或 Firefox 中的内置 Web 开发人员工具,它们都有一个小区域可以显示(Chrome 上的 Rendered Fonts Pane 或 Fonts tab on Firefox) 使用的确切字体。对于 Firefox,我猜 this code被使用了,它似乎在调用内部 API。

我正在寻找任何符合 DOM(或特定于 vendor )的方式来从 JavaScript 领域或其他方面获取准确的字体。如果这意味着编写浏览器扩展/附加组件来提供 API/注入(inject)信息/任何页面内代码访问的内容,那是最坏的情况,但可以接受。

最佳答案

您可以使用 hack:主要思想是将内联元素的大小与某些给定字体进行比较。一个应该使用完整的字体系列值,另一个应该只使用一个字体系列。这是 a proof of concept效果很好。

// Look at the fiddle for full working code
function createFontTester(fontFamily) {
  var container = document.createElement('div');
  var tester = document.createElement('div');

  container.style.position = 'absolute';
  container.style.overflow = 'auto';
  container.style.visibility = 'hidden';

  tester.style.fontFamily = fontFamily;
  tester.style.display = 'inline';
  tester.style.visibility = 'hidden';

  // The size should be big enough to make a visual difference
  tester.style.fontSize = '100px'; 

  // Reset and prevent line breaks
  tester.style.fontWeight = 'normal';
  tester.style.fontStyle = 'normal';
  tester.style.letterSpacing = 'normal';
  tester.style.lineHeight = 'normal';
  tester.style.whiteSpace = 'nowrap';

  document.body.appendChild(container);
  container.appendChild(tester);

  return tester;
}

请注意,有些字体非常相似,以至于大多数字符占用相同的空间。以 Helvetica 和 Arial 为例:字符宽度基本相同,高度略有不同,所以我使用了大字体。

这种方法可能不是万无一失的,但它适用于我能想到的所有字体系列。

更新:我做了this little library在 Github 上处理更多用例。

关于javascript - 获取浏览器中渲染文本的确切字体,可能使用浏览器扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32854083/

相关文章:

javascript - meteor 检测集合中字段的存在

javascript - SVG 中形状的缩小和居中

html - 从 Firefox 中的 html 页面或从 Firefox 扩展调用 linux 命令

javascript - JavaScript 文件中的 XML 错误

javascript - ExtJS 和 Zend Framework MVC

android - 移动设备上侧边栏定位的 CSS 问题

javascript - xmlhttprequest - 异常 101 错误

ASP.Net FileUpload 在谷歌浏览器中不起作用

javascript - Chrome 和 Firefox 中的 Marquee 标签工作方式不同

javascript - 如何在mozilla firefox浏览器中使用javascript/asp.net刷新父页面