1. Introduction
This specification describes a font enumeration API for web browsers which may, optionally, allow users to grant access to the full set of available system fonts. For each font, low-level (byte-oriented) access to an SFNT [SFNT] container or the equivalent provides full font data.
Web developers historically lack anything more than heuristic information about which local fonts are available for use in styling page content. Web developers often include complex lists of font-family
values in their CSS to control font fallback in a heuristic way. Generating good fallbacks is such a complex task for designers that tools have been built to help "eyeball" likely-available local matches.
Font enumeration helps:
-
Improving styling options for user-generated content.
-
Matching fonts declared by existing content.
While the web has its origins as a text-focused medium and user agents provide very high quality typography support, they have limitations that impact some classes of web-based applications:
-
System font engines (and browser stacks) may display certain glyphs differently. These differences are necessary, in general, to create fidelity with the underlying OS (so web content doesn’t "look wrong"). These differences reduce consistency for applications that span across multiple platforms, e.g. when pixel-accurate layout and rendering is required.
-
Design tools need access to font data to do their own layout in a platform-independent way, and for actions such as performing vector filters or transforms on the glyph shapes.
-
Developers may provide font selection UI based on metrics or themes, or automatic font matching based on metrics and other data, which require direct access to font data.
-
Some fonts may not be licensed for delivery over the web. For example, Linotype has a license for some fonts that only includes desktop use.
Professional-quality design and graphics tools have historically been difficult to deliver on the web. These tools provide extensive typographic features and controls as core capabilities.
This API provides these tools access to the same underlying font data that browser layout and rasterization engines use for drawing text. Examples include the OpenType glyf table for glyph vector data, the GPOS table for glyph placement, and the GSUB table for ligatures and other glyph substitution. This information is necessary for these tools in order to guarantee both platform-independence of the resulting output (by embedding vector descriptions rather than codepoints) and to enable font-based art (treating fonts as the basis for manipulated shapes).
2. Goals
The API should:
-
Provide efficient enumeration of all local fonts without blocking the main thread
-
Ensure UAs are free to return anything they like. If a browser implementation prefers, they may choose to only provide a set of default fonts built into the browser.
-
Be available from Workers
-
Allow multiple levels of privacy preservation; e.g., full access for "trusted" sites and degraded access for untrusted scenarios
-
Reflect local font access state in the Permissions API
-
Provide unique identification of families and instances (variants like "bold" and "italic"), including PostScript names
-
Enable a memory efficient implementation, avoiding leaks and copies by design
-
Restrict access to local font data to Secure Contexts and to only the top-most frame by default via the Permissions Policy spec
-
Sort any result list by font name to reduce possible fingerprinting entropy bits; e.g. .queryLocalFonts() returns an iterable which will be sorted by given font names
-
Provide access to the raw bytes of the font data. Most uses of this API will be to provide the full font data to existing libraries that only expect to consume entire font files. Providing only access to pre-parsed font table data would require developers to reassemble a blob containing all of the data in order to use such libraries.
Although Worker support is called as a goal out above, the API as specified is currently only exposed to Window contexts.
3. Examples
This section is non-normative.
3.1. Enumerating local fonts
The API allows script to enumerate local fonts, including properties about each font.
showLocalFontsButton. onclick= async function () { try { const array= await self. queryLocalFonts(); array. forEach( font=> { console. log( font. postscriptName); console. log( ` full name: ${ font. fullName} ` ); console. log( ` family: ${ font. family} ` ); console. log( ` style: ${ font. style} ` ); }); } catch ( e) { // Handle error, e.g. user cancelled the operation. console. warn( `Local font access not available: ${ e. message} ` ); } };
3.2. Styling with local fonts
Advanced creative tools can offer the ability to style text using all available local fonts. In this case, getting access to the local font name allows the user to select from a richer set of choices:
The following code populates a drop-down selection form element with the available local fonts, and could be used as part of the user interface for an editing application.
useLocalFontsButton. onclick= async function () { try { // Query for allowed local fonts. const array= await self. queryLocalFonts(); // Create an element to style. const exampleText= document. createElement( "p" ); exampleText. id= "exampleText" ; exampleText. innerText= "The quick brown fox jumps over the lazy dog" ; exampleText. style. fontFamily= "dynamic-font" ; // Create a list of fonts to select from, and a selection handler. const textStyle= document. createElement( "style" ); const fontSelect= document. createElement( "select" ); fontSelect. onchange= e=> { const postscriptName= fontSelect. value; console. log( "selected:" , postscriptName); // An example of styling using @font-face src: local matching. textStyle. textContent= ` @font-face { font-family: "dynamic-font"; src: local(" ${ postscriptName} "); }` ; }; // Populate the list with the available fonts. array. forEach( font=> { const option= document. createElement( "option" ); option. text= font. fullName; // postscriptName can be used with @font-face src: local to style elements. option. value= font. postscriptName; fontSelect. append( option); }); // Add all of the elements to the page. document. body. appendChild( textStyle); document. body. appendChild( exampleText); document. body. appendChild( fontSelect); } catch ( e) { // Handle error, e.g. user cancelled the operation. console. warn( `Local font access not available: ${ e. message} ` ); } };
3.3. Accessing font data
The API allows script to request font data.
Here we use enumeration to access specific local font data; we can use this to parse out specific tables or feed it into, e.g., WASM version of HarfBuzz or Freetype:
useLocalFontsButton. onclick= async function () { try { const array= await self. queryLocalFonts(); array. forEach( font=> { // blob() returns a Blob containing the bytes of the font. const bytes= await font. blob(); // Inspect the first four bytes, which for SFNT define the format. // Spec: https://docs.microsoft.com/en-us/typography/opentype/spec/otff#organization-of-an-opentype-font const sfntVersion= await bytes. slice( 0 , 4 ). text(); let outlineFormat= "UNKNOWN" ; switch ( sfntVersion) { case '\x00\x01\x00\x00' : case 'true' : case 'typ1' : outlineFormat= "truetype" ; break ; case 'OTTO' : outlineFormat= "cff" ; break ; } console. log( ` ${ font. fullName} outline format: ${ outlineFormat} ` ); } } catch ( e) { // Handle error. It could be a permission error. console. warn( `Local font access not available: ${ e. message} ` ); } };
Parsing font files in more detail, for example enumerating the contained tables, is beyond the scope of this specification.
3.4. Requesting specific fonts
In some cases, a web application may wish to request access to specific fonts. For example, it may be presenting previously authored content that embeds font names. The queryLocalFonts()
call takes a postscriptNames
option that scopes the request to fonts identified by PostScript names. Only fonts exactly matching the names in the list will be returned.
User agents may provide a different user interface to support this. For example, if the fingerprinting risk is deemed minimal, the request may be satisfied without prompting the user for permission. Alternately, a picker could be shown with only the requested fonts included.
// User activation is needed. requestFontsButton. onclick= async function () { try { const array= await self. queryLocalFonts({ postscriptNames: [ 'Verdana' , 'Verdana-Bold' , 'Verdana-Italic' ]}); array. forEach( font=> { console. log( `Access granted for ${ font. postscriptName} ` ); }); } catch ( e) { // Handle error. It could be a permission error. console. warn( `Local font access not available: ${ e. message} ` ); } };
4. Concepts
The user language is a valid BCP 47 language tag representing either a plausible language or the user’s most preferred language. [BCP47]
4.1. Font Representation
A font representation is some concrete representation of a font. Examples include OpenType, TrueType, bitmap fonts, Type1 fonts, SVG fonts, and future font formats. This specification defines the properties of a font representation as:
-
The data bytes, which is a byte sequence containing a serialization of the font.
note: The font representation's data bytes are generally expected to be the exact byte-by-byte representation of font files on the user’s filesystem. UAs aren’t expected to normalize the font data, so font representations would not vary across user agents for a given user on a particular OS. The lack of normalization supports the goal of enabling web applications that perform text rendering for content creation with the full fidelity of the font.
-
The PostScript name, which is a
DOMString
. This is commonly used as a unique identifier for the font during font loading, e.g. "Optima-Bold". -
The full name, which is a
DOMString
. This is usually a human-readable name used to identify the font, e.g. "Optima Bold". -
The family name, which is a
DOMString
. This defines a set of fonts that vary among attributes such as weight and slope, e.g. "Optima" -
The style name, which is a
DOMString
. This defines the variation of the font within a family, e.g. "Bold".
-
The data bytes are the SFNT [SFNT] serialization of the font.
-
The PostScript name is found in the font’s name table, in the name record with nameID = 6; if multiple localizations are available, the US English version is used if provided, or the first localization otherwise.
-
The full name is found in the font’s name table, in the name record with nameID = 4; if multiple localizations are available, the user language version is used if provided, or the first localization otherwise.
-
The family name is found in the font’s name table, in the name record with nameID = 1; if multiple localizations are available, the user language version is used if provided, or the first localization otherwise.
-
The style name is found in the font’s name table, in the name record with nameID = 2; if multiple localizations are available, the user language version is used if provided, or the first localization otherwise.
These name properties are exposed to align with property usage in [CSS-FONTS-4], e.g. @font-face, font-family, and so on. The PostScript name can be used as a unique key, for example when specifying a font when creating content or matching fonts against existing content. The full name or family name can be used for user-visible font selection UI, and the style name can be used to provide more specific selections.
A valid PostScript name is a scalar value string with length less than 64 and consisting only of characters in the range U+0021 (!) to U+007E (~) except for the 10 code units U+005B ([), U+005D (]), U+0028 LEFT PARENTHESIS, U+0029 RIGHT PARENTHESIS, U+007B ({), U+007D (}), U+003C (<), U+003E (>), U+002F (/), and U+0025 (%).
note: This is intended to match the requirements for nameID = 6 in [OPENTYPE].
4.2. System Fonts
A system font is a font that is available system-wide provided by the operating system.
To read a system font as a font representation is to provide a font representation equivalent to the font. This means providing all properties of a font representation:
-
PostScript name, which must be valid.
This operation can fail if providing a font representation is not possible.
A user agent may use any algorithm to provide a font representation for a system font. In practice, contemporary operating systems and system APIs support fonts that are persisted in SFNT [SFNT] font file formats, such as OpenType, TrueType, Web Open Font Format, etc. which satisfy these requirements, as well as the means to efficiently enumerate font collections with these common name properties provided for each font.
-
Let fonts be a list of all system fonts.
-
Let result be a new list.
-
For each font in fonts.
-
Let representation be font read as a font representation. On failure, continue.
-
If the user agent determines that the user should never expose the font to the web, then it may continue.
-
Append representation to result.
-
-
Return result.
5. Permissions Integration
Enumeration of local fonts requires a permission to be granted.
5.1. Permissions
The Local Font Access API is a default powerful feature that is identified by the name "local-fonts
".
When the queryLocalFonts()
API is invoked, the user agent may present a list of font choices, a yes/no choice, or other interface options. The user agent should present the results of the choice in the permission in an appropriate way. For example, if the user has selected a set of fonts to expose to the site and further API calls will return the same set of fonts, the permission state could be "granted". If the user will be prompted again, the permission state could be "prompt".
navigator.permissions
API:
// This just queries the existing state of the permission, it does not change it. const status= await navigator. permissions. query({ name: "local-fonts" }); if ( status. state=== "granted" ) console. log( "permission was granted 👍" ); else if ( status. state=== "prompt" ) console. log( "permission will be requested" ); else console. log( "permission was denied 👎" );
5.2. Permissions policy
This specification defines a policy-controlled feature identified by the string "local-fonts"
. Its default allowlist is 'self'
.
'self'
allows usage of this feature on same-origin nested frames by default but prevents access by third-party content.
Third-party usage can be selectively enabled by adding the allow="local-fonts"
attribute to an iframe
element:
Alternatively, this feature can be disabled completely in first-party contexts by specifying the permissions policy in an HTTP response header:
See [PERMISSIONS-POLICY] for more details.
6. API
6.1. Font task source
The font task source is a new generic task source which is used for all tasks that are queued in this specification.
6.2. Font manager
- await self .
queryLocalFonts()
- await self .
queryLocalFonts
({postscriptNames
: [ ... ] }) - await self .
-
Asynchronously query for available/allowed fonts. If successful, the returned promise resolves to an array of
FontData
objects.If the method is not called while the document has transient activation (e.g. in response to a click event), the returned promise will be rejected.
The user will be prompted for permission for access local fonts or to select fonts to provide to the site. If the permission is not granted, the returned promise will rejected.
If the
postscriptNames
option is given, then only fonts with matching PostScript names will be included in the results.
[SecureContext ]partial interface Window {Promise <sequence <FontData >>queryLocalFonts (optional QueryOptions = {}); };
options dictionary {
QueryOptions sequence <DOMString >; };
postscriptNames
queryLocalFonts(options)
method steps are:
-
Let promise be a new promise.
-
Let descriptor be a
PermissionDescriptor
with itsname
set to"local-fonts"
. -
If this’s relevant settings object's origin is an opaque origin, then reject promise with a "
SecurityError
"DOMException
, and return promise. -
If this’s relevant global object's associated Document is not allowed to use the policy-controlled feature named
"local-fonts"
, then reject promise with a "SecurityError
"DOMException
, and return promise. -
If this’s relevant global object does not have transient activation, then reject promise with a "
SecurityError
"DOMException
, and return promise. -
Otherwise, run these steps in parallel:
-
Let system fonts be the result of getting all system font representations.
-
Let selectable fonts be a new list.
-
For each font representation in system fonts, run these steps:
-
Let postscriptName be representation’s PostScript name.
-
Assert: postscriptName is a valid PostScript name.
-
If options[
"postscriptNames"
] exists and options["postscriptNames"
] does not contain postscriptName, then continue. -
Append a new
FontData
instance associated with representation to selectable fonts.
-
-
Prompt the user to choose one or more items from selectable fonts, with descriptor and allowMultiple set to true, and let result be the result. User agents may present a yes/no choice instead of a list of choices, and in that case they should set result to selectable fonts.
-
If result is
"denied"
, then reject promise with a "NotAllowedError
"DOMException
, and abort these steps. -
Sort result in ascending order by using
postscriptName
as the sort key and store the result as result. -
Queue a task on the font task source to resolve promise with result.
-
-
Return promise.
Move to WindowOrWorkerGlobalScope
and sort out permission issues.
6.3. The FontData
interface
A FontData
provides details about a font face. Each FontData
has an associated font representation.
- fontdata .
postscriptName
-
The PostScript name for the font. Example: "
Arial-Bold
". - fontdata .
fullName
-
The full font name, including family subfamily names. Example: "
Arial Bold
" - fontdata .
family
-
The font family name. This corresponds with the CSS font-family property. Example: "
Arial
" - fontdata .
style
-
The font style (or subfamily) name. Example: "
Regular
", "Bold Italic
"
[Exposed =Window ]interface {
FontData Promise <Blob >blob (); // Namesreadonly attribute USVString postscriptName ;readonly attribute USVString fullName ;readonly attribute USVString family ;readonly attribute USVString style ; };
postscriptName
getter steps are:
-
Let postscriptName be this's PostScript name.
-
Assert: postscriptName is a valid PostScript name.
-
Return postscriptName.
The fullName
getter steps are to return this's associated font representation's full name.
The family
getter steps are to return this's associated font representation's family name.
The style
getter steps are to return this's associated font representation's style name.
Consider making FontData
serializable objects so that the results of queryLocalFonts()
can be passed to Workers.
- await blob = fontdata .
blob()
-
Request the underlying bytes of a font. The result blob contains data bytes.
The blob()
method steps are:
-
Let realm be this's relevant Realm.
-
Let promise be a new promise in realm.
-
Run these steps in parallel:
-
Let bytes be this's associated font representation's data bytes.
-
Let type be `
application/octet-stream
`. -
Queue a task on the font task source to:
-
Let blob be a new
Blob
in realm whose contents are bytes andtype
attribute is type. -
Resolve promise with blob.
-
-
Return promise.
7. Internationalization considerations
Document internationalization considerations other than string localization, e.g. https://github.com/WICG/local-font-access/issues/72, https://github.com/WICG/local-font-access/issues/59, etc.
7.1. Font Names
The `name
` table in OpenType fonts allows names (family, subfamily, etc) to have multilingual strings, using either platform-specific numeric language identifiers or language-tag strings conforming to [BCP47]. For example, a font could have family name strings defined for both `en-US
` and `zh-Hant-HK
`.
The FontData
properties postscriptName
, fullName
, family
, and style
are provided by this API simply as strings, using either the US English localization or the user language localization depending on the name, or the first localization as a fallback.
Web applications that need to provide names in other languages can request and parse the `name
` table directly.
Should we define an option to the queryLocalFonts()
method to specify the desired language for strings (e.g. {lang: 'zh'}
), falling back to `en-US
` if not present? Or provide access to all the names, e.g. as a map from [BCP47] language tag to name? [Issue #69]
8. Accessibility considerations
There are no known accessibility impacts of this feature.
9. Security considerations
There are no known security impacts of this feature.
10. Privacy considerations
10.1. Fingerprinting
The font data includes:
-
Fonts included in the operating system distribution.
-
Fonts installed by particular applications installed on the system, for example office suites.
-
Fonts directly installed by the system administrator and/or end user.
-
The version of the font installed on the system, obtained via the font data.
This provides several "bits of entropy" to distinguish users.
User agents could mitigate this in certain cases (e.g. when the permission is denied, or in Private Browsing / "incognito" mode) by providing an enumeration of a fixed set of fonts provided with the user agent.
User agents may also allow the user to select a set of fonts to make available via the API.
When multiple localizations of font names are provided by a font, the user’s locale is potentially exposed through the font name. User agents should ensure that if a locale is exposed in this way, it’s the same locale that’s exposed by navigator.
.language
10.2. Identification
Users from a particular organization could have specific fonts installed. Employees of "Example Co." could all have an "Example Corporate Typeface" installed by their system administrator, which would allow distinguishing users of a site as employees.
There are services which create fonts based on handwriting samples. If these fonts are given names including personally identifiable information (e.g. "Alice’s Handwriting Font"), then personally identifiable information would be made available. This may not be apparent to users if the information is included as properties within the font, not just the font name.
11. Acknowledgements
We’d like to acknowledge the contributions of:
-
Daniel Nishi, Owen Campbell-Moore, and Mike Tsao who helped pioneer the previous local font access proposal.
-
Evan Wallace, Biru, Leah Cassidy, Katie Gregorio, Morgan Kennedy, and Noah Levin of Figma who have patiently enumerated the needs of their ambitious web product.
-
Alex Russell, who drafted the initial version of this proposal.
-
Olivier Yiptong, who provided an initial implementation and iteration on the API shape.
-
Tab Atkins, Jr. and the CSS Working Group who have provided usable base-classes which only need slight extension to enable these cases.
-
Dominik Röttsches and Igor Kopylov for their thoughtful feedback.
-
We would like to express our gratitude to former editor Emil A. Eklund, who passed away in 2020. Emil was instrumental in getting this proposal underway, providing technical guidance, and championing the needs of users and developers.
Special thanks (again!) to Tab Atkins, Jr. for creating and maintaining Bikeshed, the specification authoring tool used to create this document.
And thanks to Anne van Kesteren, Chase Phillips, Domenic Denicola, Dominik Röttsches, Igor Kopylov, Jake Archibald, and Jeffrey Yasskin for suggestions, reviews, and other feedback.