### window.queryLocalFonts() Source: https://context7.com/wicg/local-font-access/llms.txt Enumerates locally installed fonts on the user's system. This method requires transient user activation and returns an array of FontData objects. ```APIDOC ## window.queryLocalFonts() ### Description Prompts the user for permission and returns an array of FontData objects representing available local fonts. ### Parameters #### Request Body - **postscriptNames** (Array) - Optional - An array of PostScript names to filter the requested fonts. ### Response #### Success Response (200) - **fonts** (Array) - An array of objects containing font metadata (postscriptName, fullName, family, style). ``` -------------------------------- ### Build a Font Picker UI Source: https://context7.com/wicg/local-font-access/llms.txt Creates a dynamic dropdown interface to select and apply local fonts using the @font-face rule. ```javascript // Complete font picker implementation async function createFontPicker(containerElement) { const fonts = await window.queryLocalFonts(); // Create UI elements const select = document.createElement('select'); const preview = document.createElement('p'); const style = document.createElement('style'); preview.id = 'fontPreview'; preview.textContent = 'The quick brown fox jumps over the lazy dog'; preview.style.fontSize = '24px'; preview.style.fontFamily = 'dynamic-font'; // Populate dropdown with font options fonts.forEach(font => { const option = document.createElement('option'); option.value = font.postscriptName; option.textContent = `${font.fullName} (${font.family} - ${font.style})`; select.appendChild(option); }); // Handle font selection select.addEventListener('change', (e) => { const postscriptName = e.target.value; // Update @font-face to use selected local font style.textContent = ` @font-face { font-family: "dynamic-font"; src: local("${postscriptName}"); } `; console.log(`Applied font: ${postscriptName}`); }); // Initialize with first font if (fonts.length > 0) { select.dispatchEvent(new Event('change')); } containerElement.appendChild(style); containerElement.appendChild(select); containerElement.appendChild(preview); return { select, preview, fonts }; } // Usage document.getElementById('loadFonts').onclick = () => { createFontPicker(document.getElementById('pickerContainer')); }; ``` -------------------------------- ### Style Text Using Available Local Fonts Source: https://github.com/wicg/local-font-access/blob/main/README.md This snippet shows how to style text using local fonts. It queries for available fonts, creates a dropdown for font selection, and dynamically applies styles using @font-face with local font matching. User activation is required. ```javascript // User activation is required. 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 => { console.log("selected:", fontSelect.value); // 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(metadata => { const option = document.createElement("option"); option.text = metadata.fullName; // postscriptName works well as an identifier of sorts. // It is unique as returned by the API, the OpenType spec expects // it to be in ASCII, and it can be used by @font-face src: local // matching to be used to style elements. option.value = metadata.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}`); } }; ``` -------------------------------- ### Asynchronously Query and Iterate Local Fonts Source: https://github.com/wicg/local-font-access/blob/main/README.md This snippet demonstrates how to asynchronously query for available local fonts and iterate through their metadata. User activation is required to initiate the query. Errors, such as user cancellation, are handled. ```javascript // Asynchronous Query and Iteration // User activation is required. showLocalFontsButton.onclick = async function() { // This sketch returns individual FontMetadata instances rather than families: // In the future, query() could take filters e.g. family name, and/or options // e.g. locale. try { const array = await self.queryLocalFonts(); array.forEach(metadata => { console.log(metadata.postscriptName); console.log(` full name: ${metadata.fullName}`); console.log(` family: ${metadata.family}`); console.log(` style: ${metadata.style}`); console.log(` italic: ${metadata.italic}`); console.log(` stretch: ${metadata.stretch}`); console.log(` weight: ${metadata.weight}`); }); } catch(e) { // Handle error, e.g. user cancelled the operation. console.warn(`Local font access not available: ${e.message}`); } }; ``` -------------------------------- ### Verify Local Font Access Environment Source: https://context7.com/wicg/local-font-access/llms.txt Check for secure context, API support, and iframe permission status before attempting to query fonts. ```javascript // Check if running in allowed context function checkFontAccessAllowed() { // Verify secure context if (!window.isSecureContext) { console.error('Local Font Access requires secure context (HTTPS)'); return false; } // Verify API availability if (typeof window.queryLocalFonts !== 'function') { console.error('Local Font Access API not supported'); return false; } // Check if in cross-origin iframe without permission if (window.self !== window.top) { console.log('Running in iframe - ensure allow="local-fonts" is set'); } return true; } ``` -------------------------------- ### Enumerate All Local Fonts Source: https://context7.com/wicg/local-font-access/llms.txt Lists all available local fonts with their metadata. Requires transient user activation and secure context. Handles potential security and permission errors. ```javascript async function enumerateAllFonts() { try { const fonts = await window.queryLocalFonts(); fonts.forEach(font => { console.log(`PostScript Name: ${font.postscriptName}`); console.log(`Full Name: ${font.fullName}`); console.log(`Family: ${font.family}`); console.log(`Style: ${font.style}`); console.log('---'); }); return fonts; } catch (error) { if (error.name === 'SecurityError') { console.error('Permission denied or not in secure context'); } else if (error.name === 'NotAllowedError') { console.error('User denied font access permission'); } throw error; } } // Attach to button click (requires user activation) document.getElementById('listFontsBtn').addEventListener('click', enumerateAllFonts); ``` -------------------------------- ### Use Font Data with WebAssembly Source: https://context7.com/wicg/local-font-access/llms.txt Loads local font binary data into a WebAssembly module for advanced text processing. ```javascript // Load font into a WASM text rendering library async function loadFontIntoWasm(harfbuzzModule) { const fonts = await window.queryLocalFonts({ postscriptNames: ['Arial-BoldMT'] }); if (fonts.length === 0) { throw new Error('Requested font not available'); } const font = fonts[0]; const blob = await font.blob(); const arrayBuffer = await blob.arrayBuffer(); const fontData = new Uint8Array(arrayBuffer); // Allocate memory in WASM heap const fontPtr = harfbuzzModule._malloc(fontData.length); harfbuzzModule.HEAPU8.set(fontData, fontPtr); // Create HarfBuzz font face const hbBlob = harfbuzzModule._hb_blob_create( fontPtr, fontData.length, 2, // HB_MEMORY_MODE_WRITABLE fontPtr, harfbuzzModule._free ); const hbFace = harfbuzzModule._hb_face_create(hbBlob, 0); const hbFont = harfbuzzModule._hb_font_create(hbFace); console.log(`Loaded ${font.fullName} into HarfBuzz`); return { font: hbFont, face: hbFace, blob: hbBlob, metadata: { postscriptName: font.postscriptName, fullName: font.fullName, family: font.family, style: font.style, size: fontData.length } }; } ``` -------------------------------- ### Configure Permissions Policy for Local Font Access Source: https://context7.com/wicg/local-font-access/llms.txt Use the allow attribute in iframes or HTTP headers to grant access to local fonts in cross-origin contexts. ```html ``` -------------------------------- ### Accessing Full Font Data Source: https://github.com/wicg/local-font-access/blob/main/README.md Uses the FontMetadata blob() method to retrieve raw SFNT font data. Requires user activation and handles potential permission errors. ```javascript // User activation is required. useLocalFontsButton.onclick = async function() { // This sketch returns individual FontMetadata instances rather than families: // In the future, query() could take filters e.g. family name, and/or options // e.g. locale. A user agent may return all fonts, or show UI allowing selection // of a subset of fonts. try { const array = await self.queryLocalFonts(); array.forEach(metadata => { // blob() returns a Blob containing valid and complete SFNT // wrapped font data. const sfnt = await metadata.blob(); // Slice out only the bytes we need: the first 4 bytes are the SFNT // version info. // Spec: https://docs.microsoft.com/en-us/typography/opentype/spec/otff#organization-of-an-opentype-font const sfntVersion = await sfnt.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(`${metadata.fullName} outline format: ${outlineFormat}`); } } catch(e) { // Handle error. It could be a permission error. console.warn(`Local font access not available: ${e.message}`); } }; ``` -------------------------------- ### Check Permission Status Source: https://context7.com/wicg/local-font-access/llms.txt Queries the Permissions API to determine if local font access is granted, denied, or requires a prompt. ```javascript // Check and handle permission states async function checkFontPermission() { try { const status = await navigator.permissions.query({ name: 'local-fonts' }); console.log(`Current permission state: ${status.state}`); // React to current state switch (status.state) { case 'granted': console.log('Font access already granted - can enumerate fonts'); return true; case 'prompt': console.log('User will be prompted for permission'); return null; case 'denied': console.log('Font access denied - show fallback UI'); return false; } // Listen for permission changes status.addEventListener('change', () => { console.log(`Permission changed to: ${status.state}`); updateUIForPermissionState(status.state); }); return status.state; } catch (error) { console.error('Permissions API not supported:', error); return null; } } function updateUIForPermissionState(state) { const fontPickerUI = document.getElementById('fontPicker'); const fallbackUI = document.getElementById('fallbackFonts'); if (state === 'granted') { fontPickerUI.style.display = 'block'; fallbackUI.style.display = 'none'; } else { fontPickerUI.style.display = 'none'; fallbackUI.style.display = 'block'; } } ``` -------------------------------- ### Requesting Specific Fonts Source: https://github.com/wicg/local-font-access/blob/main/README.md Queries local fonts filtered by specific PostScript names. Only fonts matching the provided list are returned. ```javascript // User activation is required. requestFontsButton.onclick = async function() { try { const array = await self.queryLocalFonts({postscriptNames: ['Verdana', 'Verdana-Bold', 'Verdana-Italic']}); array.forEach(metadata => { console.log(`Access granted for ${metadata.postscriptName}`); }); } catch(e) { // Handle error. It could be a permission error. console.warn(`Local font access not available: ${e.message}`); } }; ``` -------------------------------- ### Request Specific Fonts by PostScript Name Source: https://context7.com/wicg/local-font-access/llms.txt Requests access to a predefined list of fonts using their PostScript names. This may streamline the user permission flow. Logs granted and missing fonts. ```javascript async function requestSpecificFonts() { const requestedFonts = ['Verdana', 'Verdana-Bold', 'Verdana-Italic', 'Arial-BoldMT']; try { const fonts = await window.queryLocalFonts({ postscriptNames: requestedFonts }); // Check which fonts were granted const grantedNames = fonts.map(f => f.postscriptName); console.log('Granted fonts:', grantedNames); // Check for missing fonts const missingFonts = requestedFonts.filter(name => !grantedNames.includes(name)); if (missingFonts.length > 0) { console.warn('Fonts not available:', missingFonts); } return fonts; } catch (error) { console.error('Font access failed:', error.message); throw error; } } ``` -------------------------------- ### Access Raw Font Data (Blob) Source: https://context7.com/wicg/local-font-access/llms.txt Retrieves the raw binary data of a font as a Blob. Inspects the first few bytes of the font data to determine its outline format (CFF or TrueType). ```javascript async function inspectFontData() { const fonts = await window.queryLocalFonts(); for (const font of fonts) { const blob = await font.blob(); // Read the first 4 bytes to determine outline format const headerBytes = await blob.slice(0, 4).arrayBuffer(); const header = new Uint8Array(headerBytes); const sfntVersion = String.fromCharCode(...header); let outlineFormat; if (sfntVersion === 'OTTO') { outlineFormat = 'CFF (PostScript outlines)'; } else if (header[0] === 0x00 && header[1] === 0x01 && header[2] === 0x00 && header[3] === 0x00) { outlineFormat = 'TrueType outlines'; } else if (sfntVersion === 'true' || sfntVersion === 'typ1') { outlineFormat = 'TrueType outlines (legacy)'; } else { outlineFormat = 'Unknown format'; } console.log(`${font.fullName}`) console.log(` Size: ${blob.size} bytes`); console.log(` Format: ${outlineFormat}`); console.log(` MIME Type: ${blob.type}`); } } ``` -------------------------------- ### FontData.blob() Source: https://context7.com/wicg/local-font-access/llms.txt Retrieves the raw binary data of a specific font as a Blob, allowing for custom parsing or rendering. ```APIDOC ## FontData.blob() ### Description Retrieves the raw binary data of a font as a Blob object. ### Response #### Success Response (200) - **blob** (Blob) - The raw binary data of the font file. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.