Persian Font Fix (Vazir)

Efficiently apply Vazir font to Persian/RTL content across all websites without impacting performance.

目前為 2025-06-02 提交的版本,檢視 最新版本

// ==UserScript==
// @name         Persian Font Fix (Vazir)
// @namespace    https://greasyfork.org/en/scripts/538095-persian-font-fix-vazir
// @version      1.1.0
// @description  Efficiently apply Vazir font to Persian/RTL content across all websites without impacting performance.
// @author       TheSina
// @match        *://*/*
// @grant        GM_addStyle
// @run-at       document-start
// @license      MIT
// ==/UserScript==

(function () {
    'use strict';

    const preferredFont = `'Vazirmatn', 'Tahoma', sans-serif`;
    const persianRegex = /[\u0600-\u06FF]/;

    // Apply minimal base styles for RTL/Persian tags
    GM_addStyle(`
        [lang="fa"], *:lang(fa), [dir="rtl"],
        yt-formatted-string, yt-attributed-string {
            font-family: ${preferredFont} !important;
        }
    `);

    // Function to apply font to a single element if it contains Persian
    const applyFontIfPersian = (el) => {
        if (el.nodeType !== 1) return; // Not an element node
        if (el.hasAttribute('data-vazir-applied')) return;

        if (persianRegex.test(el.textContent || '') || persianRegex.test(el.getAttribute?.('title') || '')) {
            el.style.fontFamily = preferredFont;
            el.setAttribute('data-vazir-applied', 'true');
        }
    };

    // Observe mutations and apply font only when Persian text appears
    const observer = new MutationObserver((mutations) => {
        for (const mutation of mutations) {
            mutation.addedNodes.forEach((node) => {
                if (node.nodeType === 1) {
                    applyFontIfPersian(node);
                    node.querySelectorAll('*').forEach(applyFontIfPersian);
                }
            });
        }
    });

    window.addEventListener('DOMContentLoaded', () => {
        document.querySelectorAll('*').forEach(applyFontIfPersian);
        observer.observe(document.body, {
            childList: true,
            subtree: true,
        });
    });
})();