// ==UserScript== // @name 替换网页字体 // @author ai // @version 2.3 // @match *://*/* // @run-at document-start // @grant GM_addStyle // @grant GM_getValues // @grant GM_getValue // @grant GM_setValues // @grant GM_setValue // @grant GM_addValueChangeListener // @grant GM_listValues // @grant GM_registerMenuCommand // @grant GM_unregisterMenuCommand // @description 替换网页的字体 // @namespace https://greasyfork.org/users/22620 // @downloadURL none // ==/UserScript== (function() { 'use strict'; const DEFAULT_CONFIG = { font: '微软雅黑', exclusions: 'i, [class*="ico"], [class*="emoji"], [class*="fa-"]', enabled: true }; class FontManager { constructor() { this.config = this.loadConfig(); this.applyFont(); if (window.top === window) this.initMenu(); GM_listValues().forEach(key => { GM_addValueChangeListener(key, () => this.applyFont()) }) } loadConfig() { return GM_getValues(DEFAULT_CONFIG) } saveConfig(key, value) { if (GM_getValue(key) === value) return; GM_setValue(key, value); this.config = this.loadConfig(); } generateCSS(font) { const notSelector = this.config.exclusions.split(',') .map(s => s.trim()) .filter(Boolean) .map(s => `:not(${s})`) .join(''); return `*${notSelector} { font-family: ${font} !important; }`; } async applyFont() { // 移除旧样式 this.styleElement?.remove(); if (!this.config.enabled) return; // 注入初始字体 this.styleElement = GM_addStyle(this.generateCSS(this.config.font)); // 等待网页字体加载后更新 await document.fonts.ready; const fonts = new Set(); document.fonts.forEach(font => fonts.add(`"${font.family}"`)); const webFonts = [...fonts].join(', '); const finalFonts = webFonts ? `${this.config.font}, ${webFonts}` : this.config.font; this.styleElement.textContent = this.generateCSS(finalFonts); } initMenu() { this.menuCommands = new Map(); this.updateMenu(); } updateMenu() { // 清除旧菜单 this.menuCommands.forEach(id => GM_unregisterMenuCommand(id)); this.menuCommands.clear(); // 注册新菜单 this.menuCommands.set('enabled', GM_registerMenuCommand( this.config.enabled ? '❌ 禁用字体替换' : '✅ 启用字体替换', () => this.toggleEnabled() )); this.menuCommands.set('font', GM_registerMenuCommand('🖋️ 配置字体名称', () => this.promptConfig('font', '请输入新的字体名称') )); this.menuCommands.set('exclusions', GM_registerMenuCommand('🚫 配置排除元素列表', () => this.promptConfig('exclusions', '请输入新的排除元素选择器') )); this.menuCommands.set('reset', GM_registerMenuCommand('🗑️ 恢复默认设置', () => this.resetToDefault() )); } toggleEnabled() { this.saveConfig("enabled", !this.config.enabled); this.updateMenu(); } promptConfig(type, promptText) { const current = this.config[type]; const newValue = prompt(`${promptText}:\n(用逗号分隔,例如: ${type === 'font' ? '"微软雅黑", system-ui' : 'i, [class*="ico"]'})`, current); if (newValue) { this.saveConfig(type, newValue); } } resetToDefault() { if (confirm('确定要将所有配置恢复为默认值吗?')) { GM_setValues(DEFAULT_CONFIG); this.config = this.loadConfig(); this.applyFont(); this.updateMenu(); } } } new FontManager(); })();