在浏览器中获取呈现文本的确切字体,可能使用浏览器扩展

Get the exact font of a rendered text in the browser, maybe with a browser extension

本文关键字:浏览器 字体 扩展 获取 文本      更新时间:2023-09-26

我知道你可以通过window.getComputedStyle()获得font-family值,但这并不总是完全是浏览器用来渲染的字体。例如,如果给定的文本包含字体族不包含的(多语言)文本,浏览器将部分地使用系统字体呈现文本。

如果你看看内置的web开发工具,无论是在Chrome或Firefox中,他们都有一个小区域显示(Rendered Fonts窗格在Chrome或Fonts选项卡在Firefox)所使用的确切字体。对于Firefox,我猜使用了这段代码,它似乎调用了内部API。

我正在寻找任何dom兼容(或供应商特定)的方式,以获得确切的字体从JavaScript土地或其他。如果这意味着要编写一个浏览器扩展/附加组件来提供API/注入信息/任何页面内代码访问,这是最坏的情况,但可以接受。

您可以使用一个hack :主要思想是比较内联元素与某些给定字体的大小。一个应该使用完整的font-family值,另一个只使用单一的font-family值。这是一个非常有效的概念证明。

// 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为例:字符宽度基本相同,高度略有不同,所以我使用了较大的font-size。

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

Update:我在Github上做了这个小库,它可以处理更多的用例