// ==UserScript== // @name 外币自动转换人民币助手 // @namespace http://tampermonkey.net/ // @version 0.5.0 // @description 自动检测网页中的外币价格,实时转换为人民币显示。支持非侵入式增量更新、30+货币与欧式/缩写/区间价格、日元智能识别、Shadow DOM 设置面板与快捷键。 // @author Currency Converter Team // @match *://*/* // @grant GM_xmlhttpRequest // @grant GM_getValue // @grant GM_setValue // @grant GM_registerMenuCommand // @grant GM_unregisterMenuCommand // @grant GM_addStyle // @connect open.er-api.com // @connect api.exchangerate-api.com // @connect cdn.jsdelivr.net // @run-at document-end // @license MIT // ==/UserScript== (function(globalScope) { 'use strict'; const SCRIPT_VERSION = '0.5.0'; const PROCESSED_ATTR = 'data-cc-done'; const CONVERTED_CLASS = 'cc-converted'; const CONVERTED_GROUP_CLASS = 'cc-converted-group'; const CONTAINER_BADGE_CLASS = 'cc-container-badge'; const HIDDEN_ORIG_CLASS = 'cc-orig-hidden'; const RATES_STORAGE_KEY = 'currencyConverterRates'; const CONFIG_STORAGE_KEY = 'currencyConverterConfig'; const DEFAULT_CONFIG = { mode: 'append', // 'append' | 'replace' enabled: true, decimalPlaces: 2, cacheDuration: 6 * 3600 * 1000, // 6 hours showStatusIndicator: false, listMode: 'none', // 'none' | 'whitelist' | 'blacklist' whitelist: [], blacklist: [], autoRefreshOnModeChange: false, autoRefreshRates: true, autoRefreshInterval: 120, yenMode: 'auto', // 'auto' | 'jpy' | 'off' badgeStyle: 'pill', // 'pill' | 'minimal' | 'muted' enableShortcuts: true, debugMode: false }; // Built-in fallback rates (USD-based) so conversion works immediately even offline or before first fetch const FALLBACK_RATES = { USD: 1, CNY: 7.25, EUR: 0.92, GBP: 0.79, JPY: 153.5, HKD: 7.78, KRW: 1385, TWD: 32.3, AUD: 1.53, CAD: 1.39, SGD: 1.34, CHF: 0.88, BRL: 5.75, INR: 84.4, THB: 34.6, RUB: 97.5, TRY: 34.4, VND: 25350, MYR: 4.44, IDR: 15850, PHP: 58.6, MXN: 20.3, NZD: 1.68, PLN: 4.05, SEK: 10.7, NOK: 11.0, DKK: 6.88, AED: 3.6725, SAR: 3.75, MOP: 8.01 }; const ZERO_DECIMAL_CURRENCIES = new Set(['JPY', 'KRW', 'VND', 'IDR']); const API_ENDPOINTS = [ { name: 'open.er-api.com', url: 'https://open.er-api.com/v6/latest/USD', extract: (res) => (res && res.rates ? normalizeApiRates(res.rates) : null) }, { name: 'exchangerate-api.com', url: 'https://api.exchangerate-api.com/v4/latest/USD', extract: (res) => (res && res.rates ? normalizeApiRates(res.rates) : null) }, { name: 'jsdelivr-currency-api', url: 'https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/usd.json', extract: (res) => (res && res.usd ? normalizeApiRates(res.usd) : null) } ]; const SKIP_TAGS = new Set([ 'SCRIPT', 'STYLE', 'TEXTAREA', 'INPUT', 'SELECT', 'OPTION', 'CODE', 'PRE', 'KBD', 'SAMP', 'NOSCRIPT', 'IFRAME', 'SVG', 'MATH', 'CANVAS', 'VIDEO', 'AUDIO', 'IMG', 'BR', 'HR', 'META', 'LINK', 'HEAD', 'TITLE' ]); const CONTAINER_TAGS = new Set([ 'SPAN', 'A', 'STRONG', 'B', 'EM', 'SMALL', 'DIV', 'P', 'TD', 'TH', 'LI', 'DD', 'DT', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'BUTTON', 'LABEL', 'INS', 'DEL', 'S', 'MARK', 'FIGCAPTION' ]); const JP_KNOWN_HOSTS = [ 'amazon.co.jp', 'rakuten.co.jp', 'shopping.yahoo.co.jp', 'auctions.yahoo.co.jp', 'mercari.com', 'jp.mercari.com', 'dmm.co.jp', 'dmm.com', 'dlsite.com', 'booth.pm', 'yodobashi.com', 'biccamera.com', 'nintendo.co.jp', 'store-jp.nintendo.com', 'zozo.jp', 'uniqlo.jp', 'animate-onlineshop.jp', 'suruga-ya.jp', 'amiami.jp' ]; const CN_KNOWN_HOSTS = [ 'taobao.com', 'tmall.com', 'jd.com', 'pinduoduo.com', 'yangkeduo.com', '1688.com', 'xiaohongshu.com', 'bilibili.com', 'zhihu.com', 'weibo.com', 'douyin.com', 'meituan.com', 'ctrip.com', 'trip.com', '12306.cn' ]; const BADGE_CSS = ` .${CONVERTED_CLASS} { display: inline !important; color: #d93829 !important; background: rgba(217, 56, 41, 0.08) !important; border-radius: 4px !important; padding: 0 2px !important; margin-left: 2px !important; font-size: 0.85em !important; font-weight: 600 !important; line-height: 1.3 !important; vertical-align: baseline !important; white-space: nowrap !important; } :root[data-cc-style="minimal"] .${CONVERTED_CLASS} { background: transparent !important; padding: 0 !important; border-radius: 0 !important; } :root[data-cc-style="muted"] .${CONVERTED_CLASS} { color: #6e7781 !important; background: transparent !important; padding: 0 !important; border-radius: 0 !important; font-weight: 500 !important; } .${CONVERTED_GROUP_CLASS} { display: inline !important; } .${HIDDEN_ORIG_CLASS} { display: none !important; } @media (prefers-color-scheme: dark) { .${CONVERTED_CLASS} { color: #ff7b72 !important; background: rgba(255, 123, 114, 0.14) !important; } :root[data-cc-style="minimal"] .${CONVERTED_CLASS} { background: transparent !important; } :root[data-cc-style="muted"] .${CONVERTED_CLASS} { color: #8b949e !important; background: transparent !important; } } `; const SHADOW_UI_CSS = ` :host { all: initial; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; } * { box-sizing: border-box; } .cc-overlay { position: fixed; inset: 0; background: rgba(0, 0, 0, 0.48); z-index: 2147483646; backdrop-filter: blur(2px); } .cc-panel { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: #ffffff; color: #1f2328; border-radius: 14px; padding: 20px 22px; width: min(480px, 92vw); max-height: 86vh; overflow-y: auto; box-shadow: 0 16px 48px rgba(0, 0, 0, 0.28); z-index: 2147483647; font-size: 13.5px; line-height: 1.5; border: 1px solid #d0d7de; } .cc-header { display: flex; justify-content: space-between; align-items: flex-start; gap: 10px; margin-bottom: 14px; } .cc-title { margin: 0 0 3px 0; font-size: 17px; font-weight: 700; } .cc-sub { margin: 0; font-size: 12px; color: #59636e; } .cc-card { margin-bottom: 11px; padding: 11px 12px; background: #f6f8fa; border-radius: 10px; border: 1px solid #eaeef2; } .cc-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; } .cc-row + .cc-row { margin-top: 8px; } .cc-grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; } .cc-label-sm { font-size: 12px; color: #59636e; margin-bottom: 4px; } select, input[type="number"], input[type="text"], textarea { background: #ffffff; color: #1f2328; border: 1px solid #d0d7de; border-radius: 6px; padding: 6px 8px; font-size: 13px; font-family: inherit; } textarea { width: 100%; resize: vertical; font-size: 12px; } .cc-switch { position: relative; display: inline-block; width: 38px; height: 22px; flex-shrink: 0; cursor: pointer; } .cc-switch input { opacity: 0; width: 0; height: 0; } .cc-slider { position: absolute; inset: 0; background: #afb8c1; border-radius: 22px; transition: 0.2s; } .cc-slider::before { content: ''; position: absolute; width: 16px; height: 16px; left: 3px; bottom: 3px; background: #ffffff; border-radius: 50%; transition: 0.2s; box-shadow: 0 1px 3px rgba(0,0,0,0.2); } .cc-switch input:checked + .cc-slider { background: #1f883d; } .cc-switch input:checked + .cc-slider::before { transform: translateX(16px); } .cc-btn { padding: 8px 12px; border: none; border-radius: 7px; cursor: pointer; font-size: 12.5px; font-weight: 600; font-family: inherit; transition: opacity 0.15s; } .cc-btn:hover { opacity: 0.9; } .cc-btn-sm { padding: 5px 9px; font-size: 12px; } .cc-toast-inline { display: none; margin-bottom: 10px; padding: 7px 10px; border-radius: 7px; background: #dafbe1; color: #116329; font-size: 12px; font-weight: 500; } .cc-toast-inline.show { display: block; } .cc-pill { position: fixed; bottom: 20px; right: 20px; z-index: 2147483647; display: inline-flex; align-items: center; gap: 6px; background: #ffffff; color: #1f2328; border: 1px solid #d0d7de; border-radius: 999px; padding: 6px 11px; font-size: 12px; font-weight: 600; box-shadow: 0 3px 14px rgba(0, 0, 0, 0.14); cursor: pointer; user-select: none; } .cc-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; } .cc-float-toast { position: fixed; top: 20px; right: 20px; z-index: 2147483647; background: rgba(31, 35, 40, 0.92); color: #ffffff; padding: 8px 14px; border-radius: 8px; font-size: 13px; font-weight: 500; box-shadow: 0 4px 16px rgba(0,0,0,0.22); pointer-events: none; } @media (prefers-color-scheme: dark) { .cc-panel { background: #1c2128; color: #e6edf3; border-color: #30363d; } .cc-sub, .cc-label-sm { color: #8b949e; } .cc-card { background: #22272e; border-color: #30363d; } select, input[type="number"], input[type="text"], textarea { background: #161b22; color: #e6edf3; border-color: #30363d; } .cc-toast-inline { background: rgba(46, 160, 67, 0.18); color: #7ee787; } .cc-pill { background: #1c2128; color: #e6edf3; border-color: #30363d; } } `; // Runtime state let rateCache = { data: { ...FALLBACK_RATES }, timestamp: null, source: 'fallback', isFallback: true }; let isModifying = false; let autoRefreshTimer = null; let fetchRetryTimer = null; let fetchRetryCount = 0; let debounceTimer = null; let sliceHandle = null; let yenContextCache = null; let registeredMenuIds = []; let lastStatusMessage = '汇率已就绪'; let lastStatusType = 'success'; let lastAppliedConfigKey = ''; // Incremental tracking state const textRecordMap = new WeakMap(); const containerRecordMap = new WeakMap(); const thrashMap = new WeakMap(); let frozenElements = new WeakSet(); const activeBadges = new Set(); const activeTextRecords = new Set(); const activeContainerRecords = new Set(); const observedRoots = new WeakSet(); const styledShadowRoots = new WeakSet(); const pendingRoots = new Set(); const pendingTextNodes = new Set(); // -------------------- Storage & Logging Helpers -------------------- function safeGMGet(key, fallback) { try { if (typeof GM_getValue === 'function') { const val = GM_getValue(key, null); return val !== null && val !== undefined ? val : fallback; } } catch (e) { /* ignore */ } return fallback; } function safeGMSet(key, val) { try { if (typeof GM_setValue === 'function') { GM_setValue(key, val); } } catch (e) { /* ignore */ } } function getConfig() { const stored = safeGMGet(CONFIG_STORAGE_KEY, null); if (stored && typeof stored === 'object') { return { ...DEFAULT_CONFIG, ...stored }; } return { ...DEFAULT_CONFIG }; } function saveConfig(config) { safeGMSet(CONFIG_STORAGE_KEY, config); } function debugLog(...args) { if (!getConfig().debugMode) return; console.log('[CC DEBUG]', ...args); } function escapeHtml(str) { return String(str == null ? '' : str) .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } function applyBadgeStyle(styleName) { if (typeof document !== 'undefined' && document.documentElement && document.documentElement.setAttribute) { document.documentElement.setAttribute('data-cc-style', styleName || 'pill'); } } function injectStyles(targetDocOrShadow) { if (targetDocOrShadow && targetDocOrShadow !== document) { if (styledShadowRoots.has(targetDocOrShadow)) return; styledShadowRoots.add(targetDocOrShadow); const style = document.createElement('style'); style.textContent = BADGE_CSS; targetDocOrShadow.appendChild(style); return; } if (typeof GM_addStyle === 'function') { GM_addStyle(BADGE_CSS); } else if (document.head) { const style = document.createElement('style'); style.textContent = BADGE_CSS; document.head.appendChild(style); } } // -------------------- Rate Fetching & Caching -------------------- function normalizeApiRates(rawRates) { if (!rawRates || typeof rawRates !== 'object') return null; const normalized = {}; for (const [k, v] of Object.entries(rawRates)) { if (typeof v === 'number' && isFinite(v) && v > 0) { normalized[k.toUpperCase()] = v; } } if (!normalized.USD) normalized.USD = 1; return normalized.CNY ? normalized : null; } function loadPersistedRates() { const stored = safeGMGet(RATES_STORAGE_KEY, null); if (stored && stored.data && stored.data.CNY) { rateCache = { data: stored.data, timestamp: stored.timestamp || null, source: stored.source || 'cache', isFallback: false }; return true; } return false; } function isRateCacheFresh() { if (!rateCache.timestamp || rateCache.isFallback) return false; const duration = getConfig().cacheDuration || DEFAULT_CONFIG.cacheDuration; return (Date.now() - rateCache.timestamp) < duration; } function fetchWithGM(url) { return new Promise((resolve, reject) => { if (typeof GM_xmlhttpRequest !== 'function') { reject(new Error('GM_xmlhttpRequest unavailable')); return; } GM_xmlhttpRequest({ method: 'GET', url, timeout: 10000, onload: (response) => { if (response.status >= 200 && response.status < 300) { try { resolve(JSON.parse(response.responseText)); } catch (e) { reject(e); } } else { reject(new Error('HTTP ' + response.status)); } }, onerror: (err) => reject(err || new Error('Network error')), ontimeout: () => reject(new Error('Request timeout')) }); }); } async function fetchExchangeRates(forceRefresh = false) { if (!forceRefresh && isRateCacheFresh()) { debugLog('using fresh persisted rates from', rateCache.source); updateStatus('汇率已就绪', 'success'); return rateCache.data; } updateStatus('正在更新汇率...', 'loading'); for (const endpoint of API_ENDPOINTS) { try { const raw = await fetchWithGM(endpoint.url); const normalized = endpoint.extract(raw); if (normalized && normalized.CNY) { rateCache = { data: normalized, timestamp: Date.now(), source: endpoint.name, isFallback: false }; safeGMSet(RATES_STORAGE_KEY, { data: normalized, timestamp: rateCache.timestamp, source: endpoint.name }); fetchRetryCount = 0; clearTimeout(fetchRetryTimer); updateStatus('汇率已更新', 'success'); debugLog('rates updated from', endpoint.name, 'CNY:', normalized.CNY); return rateCache.data; } } catch (err) { debugLog('API failed:', endpoint.name, err && err.message ? err.message : err); } } // All endpoints failed: keep existing cache or fallback rates updateStatus(rateCache.isFallback ? '使用内置参考汇率' : '使用本地缓存汇率', 'error'); if (fetchRetryCount < 3) { const backoffMs = fetchRetryCount === 0 ? 30000 : fetchRetryCount === 1 ? 120000 : 300000; fetchRetryCount += 1; clearTimeout(fetchRetryTimer); fetchRetryTimer = setTimeout(async () => { await fetchExchangeRates(true); if (getConfig().enabled && shouldRunOnCurrentSite()) { refreshConvertedBadges(); } }, backoffMs); } return rateCache.data; } function setRatesForTest(ratesObj) { rateCache = { data: normalizeApiRates(ratesObj) || { ...FALLBACK_RATES }, timestamp: Date.now(), source: 'test', isFallback: false }; } // -------------------- Currency & Number Engine -------------------- function getCurrentHostname() { try { return (typeof window !== 'undefined' && window.location && window.location.hostname) || ''; } catch (e) { return ''; } } function inferKrCurrency(hostname = '') { const host = String(hostname || '').toLowerCase(); if (host.endsWith('.no') || host.includes('.no.')) return 'NOK'; if (host.endsWith('.dk') || host.includes('.dk.')) return 'DKK'; return 'SEK'; } function detectYenContext({ hostname = '', lang = '', textSample = '', yenMode = 'auto' } = {}) { if (yenMode === 'jpy') return true; if (yenMode === 'off') return false; const host = String(hostname || '').toLowerCase(); const docLang = String(lang || '').toLowerCase(); if (host.endsWith('.jp') || JP_KNOWN_HOSTS.some((h) => host === h || host.endsWith('.' + h))) { return true; } if (docLang.startsWith('ja')) { return true; } const isCnSite = host.endsWith('.cn') || docLang.startsWith('zh') || CN_KNOWN_HOSTS.some((h) => host === h || host.endsWith('.' + h)); if (isCnSite) { return false; } if (/[\u3040-\u309F\u30A0-\u30FF]/.test(textSample) || /税込|税抜|\bJPY\b/i.test(textSample)) { return true; } return false; } function getPageYenAsJpy() { const config = getConfig(); if (config.yenMode === 'jpy') return true; if (config.yenMode === 'off') return false; if (yenContextCache !== null) return yenContextCache; const hostname = getCurrentHostname(); const lang = (typeof document !== 'undefined' && document.documentElement && document.documentElement.lang) || ''; const textSample = (typeof document !== 'undefined' && document.body && document.body.textContent) ? document.body.textContent.slice(0, 4000) : ''; yenContextCache = detectYenContext({ hostname, lang, textSample, yenMode: config.yenMode }); return yenContextCache; } const INV_CHARS_RE = /[\u200B-\u200F\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/g; function parseLocalizedNumber(rawStr, code = 'USD') { if (!rawStr || typeof rawStr !== 'string') return null; let s = rawStr.replace(INV_CHARS_RE, '').trim(); let isNegative = false; if (s.startsWith('-')) { isNegative = true; s = s.slice(1).trim(); } else if (s.startsWith('+')) { s = s.slice(1).trim(); } let multiplier = 1; const magMatch = s.match(/([KMBTkmbt]|万|亿)$/); if (magMatch) { const mag = magMatch[1].toUpperCase(); s = s.slice(0, -magMatch[0].length).trim(); if (mag === 'K') multiplier = 1e3; else if (mag === 'M') multiplier = 1e6; else if (mag === 'B') multiplier = 1e9; else if (mag === 'T') multiplier = 1e12; else if (mag === '万') multiplier = 1e4; else if (mag === '亿') multiplier = 1e8; } // Remove spaces, NBSP, apostrophes used as thousands separators s = s.replace(/[\s\u00A0'’]/g, ''); if (!s || isDigitReelText(s)) return null; const hasComma = s.includes(','); const hasDot = s.includes('.'); if (hasComma && hasDot) { const lastComma = s.lastIndexOf(','); const lastDot = s.lastIndexOf('.'); if (lastComma > lastDot) { // European: 1.299,99 s = s.replace(/\./g, '').replace(',', '.'); } else { // US/UK: 1,299.99 s = s.replace(/,/g, ''); } } else if (hasComma) { const commaCount = (s.match(/,/g) || []).length; if (commaCount > 1) { s = s.replace(/,/g, ''); } else { const [intPart, fracPart] = s.split(','); if (intPart === '0' || fracPart.length !== 3) { s = s.replace(',', '.'); } else { s = s.replace(/,/g, ''); } } } else if (hasDot) { const dotCount = (s.match(/\./g) || []).length; if (dotCount > 1) { s = s.replace(/\./g, ''); } else { const [intPart, fracPart] = s.split('.'); if (ZERO_DECIMAL_CURRENCIES.has(code) && fracPart.length === 3 && intPart.length >= 1 && intPart.length <= 3 && intPart !== '0') { s = s.replace(/\./g, ''); } } } const intDigits = s.split('.')[0].replace(/\D/g, ''); if (intDigits.length > 12) return null; const num = parseFloat(s); const total = num * multiplier; if (!isFinite(total) || total <= 0 || total > 1e15) return null; return { value: total, isNegative }; } function isDigitReelText(text) { if (!text) return false; const compact = String(text).replace(/\s+/g, ''); return compact.length >= 9 && ( compact.includes('0123456789') || compact.includes('9876543210') || /012345678|123456789/.test(compact) ); } // Core number fragment: // Matches 1,299.99 | 1.299,99 | 1 299,50 | 1'250.00 | 19,99 | 19.99 | 100 | .99 const NUM_CORE = "(?:\\d{1,3}(?:[ ,.'\\u00A0’]\\d{3})+|\\d+)(?:[.,]\\d+)?|\\.\\d+"; const MAG_SUFFIX = "(?:(?=[KMBTkmbt](?![A-Za-z]))[KMBTkmbt]|[万亿])?"; const NUM_WITH_MAG = `(?:${NUM_CORE})${MAG_SUFFIX}`; const WS = '[\\s\\u00A0\\u200B-\\u200F\\u202A-\\u202E\\u2060\\u2066-\\u2069\\uFEFF]*'; const PREFIX_DOLLAR_SPECS = [ { token: 'USD\\$', code: 'USD' }, { token: 'HKD\\$', code: 'HKD' }, { token: 'NTD\\$', code: 'TWD' }, { token: 'CAD\\$', code: 'CAD' }, { token: 'AUD\\$', code: 'AUD' }, { token: 'SGD\\$', code: 'SGD' }, { token: 'NZD\\$', code: 'NZD' }, { token: 'MXN\\$', code: 'MXN' }, { token: 'MOP\\$', code: 'MOP' }, { token: 'US\\$', code: 'USD' }, { token: 'US \\$', code: 'USD' }, { token: 'HK\\$', code: 'HKD' }, { token: 'HK \\$', code: 'HKD' }, { token: 'NT\\$', code: 'TWD' }, { token: 'NT \\$', code: 'TWD' }, { token: 'TW\\$', code: 'TWD' }, { token: 'CA\\$', code: 'CAD' }, { token: 'CA \\$', code: 'CAD' }, { token: 'AU\\$', code: 'AUD' }, { token: 'AU \\$', code: 'AUD' }, { token: 'SG\\$', code: 'SGD' }, { token: 'SG \\$', code: 'SGD' }, { token: 'NZ\\$', code: 'NZD' }, { token: 'NZ \\$', code: 'NZD' }, { token: 'MX\\$', code: 'MXN' }, { token: 'MX \\$', code: 'MXN' }, { token: 'BR\\$', code: 'BRL' }, { token: 'A\\$', code: 'AUD' }, { token: 'C\\$', code: 'CAD' }, { token: 'S\\$', code: 'SGD' }, { token: 'R\\$', code: 'BRL' }, { token: `JPY${WS}[¥¥]`, code: 'JPY' }, { token: `JP${WS}[¥¥]`, code: 'JPY' }, { token: `GB${WS}£`, code: 'GBP' }, { token: `UK${WS}£`, code: 'GBP' }, { token: `EU${WS}€`, code: 'EUR' }, { token: `KR${WS}₩`, code: 'KRW' } ]; const PREFIX_DOLLAR_RE = new RegExp( `([+-])?(?:${PREFIX_DOLLAR_SPECS.map((s) => s.token).join('|')})${WS}([+-]?${NUM_WITH_MAG})`, 'gi' ); const PREFIX_CODE_LIST = [ 'USD', 'EUR', 'GBP', 'JPY', 'HKD', 'KRW', 'AUD', 'CAD', 'TWD', 'NTD', 'SGD', 'CHF', 'BRL', 'INR', 'THB', 'RUB', 'TRY', 'VND', 'MYR', 'IDR', 'PHP', 'MXN', 'NZD', 'PLN', 'SEK', 'NOK', 'DKK', 'AED', 'SAR', 'MOP', 'RM', 'Rp\\.?', 'Rs\\.?' ]; const PREFIX_CODE_RE = new RegExp( `(${PREFIX_CODE_LIST.join('|')})${WS}([+-]?${NUM_WITH_MAG})`, 'gi' ); const PREFIX_SYMBOL_MAP = { '€': 'EUR', '£': 'GBP', '₩': 'KRW', '₹': 'INR', '฿': 'THB', '₽': 'RUB', '₺': 'TRY', '₫': 'VND', '₱': 'PHP', '$': 'USD', '¥': 'JPY', '¥': 'JPY' }; const PREFIX_SYMBOL_RE = new RegExp( `([+-])?([€£₩₹฿₽₺₫₱$¥¥])${WS}([+-]?${NUM_WITH_MAG})`, 'g' ); const SUFFIX_CODE_LIST = [ 'USD', 'EUR', 'GBP', 'JPY', 'HKD', 'KRW', 'AUD', 'CAD', 'TWD', 'SGD', 'CHF', 'BRL', 'INR', 'THB', 'RUB', 'TRY', 'VND', 'MYR', 'IDR', 'PHP', 'MXN', 'NZD', 'PLN', 'SEK', 'NOK', 'DKK', 'AED', 'SAR', 'MOP' ]; const SUFFIX_TOKEN_RE = new RegExp( `([+-]?${NUM_WITH_MAG})${WS}(€|£|₩|₹|฿|₽|₺|₫|₱|円|원|zł|kr|${SUFFIX_CODE_LIST.join('|')})`, 'gi' ); const RANGE_TAIL_RE = new RegExp( `^[\\s\\u00A0]*([-–—~~])[\\s\\u00A0]*((?:[+-][\\s\\u00A0]*)?(?:${NUM_CORE})${MAG_SUFFIX})` ); function mapPrefixTokenToCode(token) { const clean = token.replace(INV_CHARS_RE, '').toUpperCase().replace(/[\s.$¥¥€£₩]/g, ''); if (clean === 'NTD' || clean === 'NT' || clean === 'TW') return 'TWD'; if (clean === 'US') return 'USD'; if (clean === 'HK') return 'HKD'; if (clean === 'CA' || clean === 'C') return 'CAD'; if (clean === 'AU' || clean === 'A') return 'AUD'; if (clean === 'SG' || clean === 'S') return 'SGD'; if (clean === 'NZ') return 'NZD'; if (clean === 'MX') return 'MXN'; if (clean === 'BR' || clean === 'R') return 'BRL'; if (clean === 'JP') return 'JPY'; if (clean === 'GB' || clean === 'UK') return 'GBP'; if (clean === 'EU') return 'EUR'; if (clean === 'KR') return 'KRW'; if (clean === 'RM') return 'MYR'; if (clean === 'RP') return 'IDR'; if (clean === 'RS') return 'INR'; return clean; } function isWordChar(ch) { return !!ch && /[A-Za-z0-9_]/.test(ch); } function isAlphaChar(ch) { return !!ch && /[A-Za-z]/.test(ch); } function isSignContextValid(text, matchIdx, hasLeadingSign) { if (!hasLeadingSign || matchIdx <= 0) return true; const prev = text[matchIdx - 1]; return !/[A-Za-z0-9]/.test(prev); } function findAllMatches(text, options = {}) { if (!text || typeof text !== 'string') return []; if (/≈-?¥/.test(text)) return []; const yenAsJpy = options.yenAsJpy !== undefined ? !!options.yenAsJpy : getPageYenAsJpy(); const hostname = options.hostname !== undefined ? options.hostname : getCurrentHostname(); const hits = []; // 1. Multi-char dollar prefixes (US$, CA$, HK$, etc.) PREFIX_DOLLAR_RE.lastIndex = 0; let m; while ((m = PREFIX_DOLLAR_RE.exec(text)) !== null) { const idx = m.index; const leadSign = m[1] || ''; if (!isSignContextValid(text, idx, !!leadSign)) continue; // Ensure not preceded by another ASCII letter (blocks ARS$50 -> S$50, EUR$100 -> R$100, BTC$ -> C$) if (!leadSign && idx > 0 && isAlphaChar(text[idx - 1])) continue; // Check right boundary if number ends with magnitude letter const endIdx = idx + m[0].length; if (endIdx < text.length && isAlphaChar(text[endIdx])) continue; const symPos = m[0].search(/[$¥¥€£₩]/); const rawPrefix = symPos >= 0 ? m[0].slice(leadSign.length, symPos + 1) : ''; const code = mapPrefixTokenToCode(rawPrefix); const numStr = (leadSign && !m[2].startsWith('-') && !m[2].startsWith('+')) ? (leadSign + m[2]) : m[2]; const parsed = parseLocalizedNumber(numStr, code); if (!parsed) continue; hits.push({ index: idx, length: m[0].length, code, amount: parsed.isNegative ? -parsed.value : parsed.value, fullMatch: m[0] }); } // 2. Prefix currency codes (USD 100, EUR 50, RM 30, Rp 15.000) PREFIX_CODE_RE.lastIndex = 0; while ((m = PREFIX_CODE_RE.exec(text)) !== null) { const idx = m.index; if (idx > 0 && isWordChar(text[idx - 1])) continue; const endIdx = idx + m[0].length; if (endIdx < text.length && isAlphaChar(text[endIdx])) continue; const code = mapPrefixTokenToCode(m[1]); const parsed = parseLocalizedNumber(m[2], code); if (!parsed) continue; hits.push({ index: idx, length: m[0].length, code, amount: parsed.isNegative ? -parsed.value : parsed.value, fullMatch: m[0] }); } // 3. Prefix single-char symbols (€, £, ₩, ₹, ฿, ₽, ₺, ₫, ₱, $, ¥, ¥) PREFIX_SYMBOL_RE.lastIndex = 0; while ((m = PREFIX_SYMBOL_RE.exec(text)) !== null) { const idx = m.index; const leadSign = m[1] || ''; const sym = m[2]; if ((sym === '¥' || sym === '¥') && !yenAsJpy) continue; if (!isSignContextValid(text, idx, !!leadSign)) continue; if ((sym === '$' || sym === '¥' || sym === '¥') && !leadSign && idx > 0 && isAlphaChar(text[idx - 1])) continue; const endIdx = idx + m[0].length; if (endIdx < text.length && isAlphaChar(text[endIdx])) continue; const code = PREFIX_SYMBOL_MAP[sym]; const numStr = (leadSign && !m[3].startsWith('-') && !m[3].startsWith('+')) ? (leadSign + m[3]) : m[3]; const parsed = parseLocalizedNumber(numStr, code); if (!parsed) continue; hits.push({ index: idx, length: m[0].length, code, amount: parsed.isNegative ? -parsed.value : parsed.value, fullMatch: m[0] }); } // 4. Suffix currency symbols & codes (19.99 €, 100 USD, 1,980円, 10,000원, 250 kr) SUFFIX_TOKEN_RE.lastIndex = 0; while ((m = SUFFIX_TOKEN_RE.exec(text)) !== null) { const idx = m.index; if (idx > 0 && isWordChar(text[idx - 1])) continue; const suffix = m[2]; const endIdx = idx + m[0].length; if (/^[A-Za-z]+$/.test(suffix) && endIdx < text.length && isWordChar(text[endIdx])) continue; let code; if (suffix === '円') code = 'JPY'; else if (suffix === '원') code = 'KRW'; else if (suffix.toLowerCase() === 'zł') code = 'PLN'; else if (suffix.toLowerCase() === 'kr') code = inferKrCurrency(hostname); else if (PREFIX_SYMBOL_MAP[suffix]) code = PREFIX_SYMBOL_MAP[suffix]; else code = suffix.toUpperCase(); const parsed = parseLocalizedNumber(m[1], code); if (!parsed) continue; hits.push({ index: idx, length: m[0].length, code, amount: parsed.isNegative ? -parsed.value : parsed.value, fullMatch: m[0] }); } if (hits.length === 0) return []; // Deduplicate overlapping matches: earliest index first, longest match first hits.sort((a, b) => a.index - b.index || b.length - a.length); const deduped = []; let lastEnd = -1; for (const h of hits) { if (h.index >= lastEnd) { deduped.push(h); lastEnd = h.index + h.length; } } // Merge price ranges like "$10 - 20" or "€50~100" when second number has no currency symbol for (let i = 0; i < deduped.length; i++) { const curr = deduped[i]; const currEnd = curr.index + curr.length; const nextLimit = i + 1 < deduped.length ? deduped[i + 1].index : text.length; const tail = text.slice(currEnd, nextLimit); const rm = tail.match(RANGE_TAIL_RE); if (!rm) continue; const afterEnd = currEnd + rm[0].length; if (afterEnd < text.length && (text[afterEnd] === '%' || isAlphaChar(text[afterEnd]))) continue; const parsedEnd = parseLocalizedNumber(rm[2].replace(/\s+/g, ''), curr.code); if (!parsedEnd) continue; curr.isRange = true; curr.separator = rm[1]; curr.amountEnd = parsedEnd.isNegative ? -parsedEnd.value : parsedEnd.value; curr.length += rm[0].length; curr.fullMatch = text.slice(curr.index, curr.index + curr.length); } return deduped; } function convertCurrency(amount, fromCurrency, customRates) { const rates = customRates || rateCache.data; if (!rates) return null; if (fromCurrency === 'CNY') return amount; if (rates[fromCurrency] && rates.CNY) { return (amount / rates[fromCurrency]) * rates.CNY; } return null; } function formatAmountCore(absAmt, decimalPlaces = 2) { if (absAmt >= 1e8) return (absAmt / 1e8).toFixed(2) + '亿'; if (absAmt >= 1e5) return (absAmt / 1e4).toFixed(1) + '万'; if (absAmt >= 1e4) return (absAmt / 1e4).toFixed(decimalPlaces) + '万'; if (absAmt > 0 && absAmt < 0.01) { return Number(absAmt.toPrecision(2)).toFixed(6).replace(/0+$/, '').replace(/\.$/, ''); } return absAmt.toFixed(decimalPlaces); } function formatPrice(amt, decimalPlaces) { const d = decimalPlaces !== undefined ? decimalPlaces : (getConfig().decimalPlaces ?? 2); if (amt < 0) { return '-≈¥' + formatAmountCore(Math.abs(amt), d); } return '≈¥' + formatAmountCore(amt, d); } function formatMatchResult(match, decimalPlaces) { const d = decimalPlaces !== undefined ? decimalPlaces : (getConfig().decimalPlaces ?? 2); const startCny = convertCurrency(match.amount, match.code); if (startCny === null) return null; if (match.isRange && match.amountEnd !== undefined) { const endCny = convertCurrency(match.amountEnd, match.code); if (endCny === null) return formatPrice(startCny, d); const startPrefix = startCny < 0 ? '-≈¥' : '≈¥'; const endPrefix = endCny < 0 ? '-' : ''; return `${startPrefix}${formatAmountCore(Math.abs(startCny), d)}-${endPrefix}${formatAmountCore(Math.abs(endCny), d)}`; } return formatPrice(startCny, d); } // -------------------- DOM Scanning & Non-Destructive Rendering -------------------- function isHiddenHelperElement(el) { if (!el || el.nodeType !== 1) return false; if (el.hidden) return true; if (el.classList) { if (el.classList.contains('a-offscreen') || el.classList.contains('sr-only') || el.classList.contains('visually-hidden') || el.classList.contains(CONVERTED_CLASS) || el.classList.contains(HIDDEN_ORIG_CLASS)) { return true; } } return false; } function isOwnUIElement(el) { if (!el || el.nodeType !== 1) return false; return el.id === 'currency-converter-ui-host' || el.id === 'currency-converter-pill-host' || el.id === 'currency-converter-toast-host' || el.id === 'currency-converter-panel' || el.id === 'currency-converter-overlay' || el.id === 'currency-converter-status'; } function isSkippedElement(el) { if (!el) return true; if (el.nodeType !== 1) return false; if (SKIP_TAGS.has(el.tagName)) return true; if (el.isContentEditable) return true; if (isOwnUIElement(el)) return true; if (isHiddenHelperElement(el)) return true; if (el.getAttribute && el.getAttribute(PROCESSED_ATTR) === '1') return true; if (el.classList && (el.classList.contains(CONVERTED_CLASS) || el.classList.contains(CONVERTED_GROUP_CLASS))) return true; if (el.closest && (el.closest('.' + CONVERTED_CLASS) || el.closest('.' + CONVERTED_GROUP_CLASS) || el.closest('#currency-converter-panel'))) { return true; } return false; } function quickCheck(text) { if (!text || text.length < 2) return false; if (/≈-?¥/.test(text)) return false; if (/[$€£₩₹฿₽₺₫₱¥¥円원]/.test(text)) return true; if (/(?:USD|EUR|GBP|JPY|HKD|KRW|AUD|CAD|TWD|NTD|SGD|CHF|BRL|INR|THB|RUB|TRY|VND|MYR|IDR|PHP|MXN|NZD|PLN|SEK|NOK|DKK|AED|SAR|MOP|RM|Rp|Rs|zł|kr)/i.test(text)) { return true; } return false; } function shouldThrottleElement(el) { if (!el || frozenElements.has(el)) return true; const now = Date.now(); const entry = thrashMap.get(el); if (!entry || (now - entry.start) > 4000) { thrashMap.set(el, { count: 1, start: now }); return false; } entry.count += 1; if (entry.count >= 3) { frozenElements.add(el); debugLog('throttled oscillating element:', el.tagName || el.nodeName); return true; } return false; } function createBadgeElement(text, titleText, isContainerBadge = false) { const span = document.createElement('span'); span.className = isContainerBadge ? `${CONVERTED_CLASS} ${CONTAINER_BADGE_CLASS} notranslate` : `${CONVERTED_CLASS} notranslate`; span.setAttribute(PROCESSED_ATTR, '1'); span.setAttribute('translate', 'no'); span.textContent = text; if (titleText) span.title = titleText; activeBadges.add(span); return span; } function buildTooltip(match) { const rate = rateCache.data && rateCache.data[match.code]; const cny = rateCache.data && rateCache.data.CNY; if (!rate || !cny) return ''; const unitRate = (cny / rate).toFixed(4); return `1 ${match.code} ≈ ${unitRate} CNY (${match.fullMatch.trim()})`; } function processTextNode(node) { if (!node || node.nodeType !== 3) return false; const parent = node.parentElement || node.parentNode; if (!parent || isSkippedElement(parent) || frozenElements.has(parent)) return false; const existing = textRecordMap.get(node); const text = node.nodeValue; const config = getConfig(); // Already processed and source unchanged -> skip without touching DOM! if (existing) { if (existing.mode === 'replace') { if (text === existing.replacedText) return false; } else if (existing.mode === 'append') { if (text === existing.originalText && existing.badge && existing.badge.isConnected) { return false; } } const sameSource = existing.mode === 'append' && text === existing.originalText; if (existing.badge && existing.badge.parentNode) { existing.badge.parentNode.removeChild(existing.badge); activeBadges.delete(existing.badge); } textRecordMap.delete(node); activeTextRecords.delete(existing); if (sameSource && shouldThrottleElement(parent)) return false; } if (!quickCheck(text)) return false; const matches = findAllMatches(text); if (matches.length === 0) return false; isModifying = true; try { if (config.mode === 'replace') { let newText = text; let offset = 0; for (const m of matches) { const formatted = formatMatchResult(m, config.decimalPlaces); if (!formatted) continue; const start = m.index + offset; newText = newText.slice(0, start) + formatted + newText.slice(start + m.length); offset += formatted.length - m.length; } if (newText === text) return false; node.nodeValue = newText; const rec = { type: 'text', node, mode: 'replace', originalText: text, replacedText: newText, matches }; textRecordMap.set(node, rec); activeTextRecords.add(rec); return true; } // Append mode: fast non-destructive path for single-match short text nodes (keeps TextNode 100% intact) const single = matches[0]; if (matches.length === 1 && text.length <= 60) { const formatted = formatMatchResult(single, config.decimalPlaces); if (!formatted) return false; const badge = createBadgeElement(formatted, buildTooltip(single), false); if (node.nextSibling) { parent.insertBefore(badge, node.nextSibling); } else { parent.appendChild(badge); } const rec = { type: 'text', node, mode: 'append', originalText: text, badge, matches }; textRecordMap.set(node, rec); activeTextRecords.add(rec); return true; } // Multi-match or mid-sentence append: wrap with inline group fragment const fragment = document.createDocumentFragment(); let cursor = 0; let changed = false; const createdGroups = []; for (const m of matches) { const formatted = formatMatchResult(m, config.decimalPlaces); if (!formatted) continue; changed = true; const end = m.index + m.length; if (m.index > cursor) { fragment.appendChild(document.createTextNode(text.slice(cursor, m.index))); } const group = document.createElement('span'); group.className = `${CONVERTED_GROUP_CLASS} notranslate`; group.setAttribute(PROCESSED_ATTR, '1'); group.setAttribute('translate', 'no'); const origNode = document.createTextNode(text.slice(m.index, end)); const badge = createBadgeElement(formatted, buildTooltip(m), false); group.appendChild(origNode); group.appendChild(badge); fragment.appendChild(group); createdGroups.push({ group, origText: text.slice(m.index, end), badge, match: m }); cursor = end; } if (!changed) return false; if (cursor < text.length) { fragment.appendChild(document.createTextNode(text.slice(cursor))); } parent.replaceChild(fragment, node); for (const g of createdGroups) { const rec = { type: 'group', group: g.group, origText: g.origText, badge: g.badge, match: g.match }; activeTextRecords.add(rec); } return true; } finally { isModifying = false; } } function collectPlainContainerText(el) { let out = ''; for (const child of el.childNodes) { if (child.nodeType === 3) { out += child.nodeValue || ''; } else if (child.nodeType === 1) { if (SKIP_TAGS.has(child.tagName) || isHiddenHelperElement(child)) continue; out += collectPlainContainerText(child); } } return out; } function collectOdometerSafeText(el) { if (!el) return ''; const ariaLabel = el.getAttribute && el.getAttribute('aria-label'); if (ariaLabel && !isDigitReelText(ariaLabel)) { return ariaLabel; } let out = ''; for (const child of el.childNodes) { if (child.nodeType === 3) { const v = child.nodeValue || ''; if (!isDigitReelText(v)) out += v; continue; } if (child.nodeType !== 1) continue; if (SKIP_TAGS.has(child.tagName)) continue; if (child.classList && (child.classList.contains(CONVERTED_CLASS) || child.classList.contains(HIDDEN_ORIG_CLASS))) continue; const childAriaLabel = child.getAttribute && child.getAttribute('aria-label'); const childText = child.textContent || ''; if (childAriaLabel && isDigitReelText(childText)) { out += childAriaLabel; continue; } if (child.classList && (child.classList.contains('sr-only') || child.classList.contains('visually-hidden') || child.classList.contains('a-offscreen'))) { out += childText; continue; } if ((child.getAttribute && child.getAttribute('aria-hidden') === 'true') || isDigitReelText(childText)) { continue; } out += collectOdometerSafeText(child); } return out; } function getContainerVisibleText(el) { if (!el) return ''; const rawAll = el.textContent || ''; const out = isDigitReelText(rawAll) ? collectOdometerSafeText(el) : collectPlainContainerText(el); const normalized = out.replace(/\s+/g, ' ').trim(); return isDigitReelText(normalized) ? '' : normalized; } function hasConvertedDescendant(el) { if (!el || !el.querySelector) return false; return !!el.querySelector('.' + CONVERTED_CLASS + ', .' + CONVERTED_GROUP_CLASS); } function hasSingleChildWithFullMatch(el) { if (!el || !el.children) return false; for (const child of el.children) { if (isHiddenHelperElement(child) || SKIP_TAGS.has(child.tagName)) continue; const childText = getContainerVisibleText(child); if (childText && quickCheck(childText) && findAllMatches(childText).length > 0) { return true; } } return false; } function isContainerTag(tagName) { if (!tagName) return false; return CONTAINER_TAGS.has(tagName) || tagName.includes('-'); } function processSplitContainer(el) { if (!el || el.nodeType !== 1) return false; if (!isContainerTag(el.tagName)) return false; if (isSkippedElement(el) || frozenElements.has(el)) return false; if (!el.children || el.children.length === 0 || el.children.length > 6) return false; const existing = containerRecordMap.get(el); const visibleText = getContainerVisibleText(el); const config = getConfig(); if (existing) { if (visibleText === existing.sourceText && existing.badge && existing.badge.isConnected) { return false; } // Legitimate price update (e.g. user switched 100 -> 200 -> 500): update badge in-place! if (visibleText !== existing.sourceText && existing.mode === 'append' && existing.badge && existing.badge.isConnected) { const newMatches = visibleText && visibleText.length >= 2 && visibleText.length <= 60 && quickCheck(visibleText) ? findAllMatches(visibleText) : []; if (newMatches.length > 0 && !hasSingleChildWithFullMatch(el)) { const parts = newMatches.map((m) => formatMatchResult(m, config.decimalPlaces)).filter(Boolean); if (parts.length > 0) { isModifying = true; try { existing.badge.textContent = parts.join(' / '); existing.badge.title = newMatches.map((m) => buildTooltip(m)).filter(Boolean).join(' | '); existing.sourceText = visibleText; existing.matches = newMatches; } finally { isModifying = false; } return true; } } } // Otherwise clean old badge; only throttle if external actor detached badge while source didn't change const sameSource = visibleText === existing.sourceText; if (existing.hiddenEls) { for (const h of existing.hiddenEls) { if (h.classList) h.classList.remove(HIDDEN_ORIG_CLASS); } } if (existing.badge && existing.badge.parentNode) { existing.badge.parentNode.removeChild(existing.badge); activeBadges.delete(existing.badge); } containerRecordMap.delete(el); activeContainerRecords.delete(existing); if (sameSource && shouldThrottleElement(el)) return false; } if (hasConvertedDescendant(el)) return false; if (!visibleText || visibleText.length < 2 || visibleText.length > 60) return false; if (!quickCheck(visibleText)) return false; const matches = findAllMatches(visibleText); if (matches.length === 0) return false; if (hasSingleChildWithFullMatch(el)) return false; const formattedParts = []; for (const m of matches) { const f = formatMatchResult(m, config.decimalPlaces); if (f) formattedParts.push(f); } if (formattedParts.length === 0) return false; const badgeText = formattedParts.join(' / '); const tooltip = matches.map((m) => buildTooltip(m)).filter(Boolean).join(' | '); isModifying = true; try { const hiddenEls = []; if (config.mode === 'replace') { for (const child of Array.from(el.childNodes)) { if (child.nodeType === 1 && !isHiddenHelperElement(child)) { child.classList.add(HIDDEN_ORIG_CLASS); hiddenEls.push(child); } else if (child.nodeType === 3 && child.nodeValue && child.nodeValue.trim()) { const wrapper = document.createElement('span'); wrapper.className = HIDDEN_ORIG_CLASS; wrapper.textContent = child.nodeValue; el.replaceChild(wrapper, child); hiddenEls.push(wrapper); } } } const badge = createBadgeElement(badgeText, tooltip, true); el.appendChild(badge); const rec = { type: 'container', el, mode: config.mode, sourceText: visibleText, badge, matches, hiddenEls }; containerRecordMap.set(el, rec); activeContainerRecords.add(rec); return true; } finally { isModifying = false; } } function collectNodesForScan(root) { const textNodes = []; const containers = []; const shadowRoots = []; function visit(node) { if (!node) return; if (node.nodeType === 3) { if (node.nodeValue && node.nodeValue.trim().length >= 2) { const parent = node.parentElement || node.parentNode; if (parent && !isSkippedElement(parent)) { textNodes.push(node); } } return; } if (node.nodeType !== 1 && node.nodeType !== 11) return; // Element or DocumentFragment/ShadowRoot if (node.nodeType === 1) { if (isSkippedElement(node)) return; if (node.shadowRoot) { shadowRoots.push(node.shadowRoot); } if (isContainerTag(node.tagName) && node.children && node.children.length > 0) { containers.push(node); } } for (const child of node.childNodes) { visit(child); } } visit(root); return { textNodes, containers, shadowRoots }; } function scanRoot(root) { if (!root) return 0; const { textNodes, containers, shadowRoots } = collectNodesForScan(root); let convertedCount = 0; for (const tn of textNodes) { try { if (processTextNode(tn)) convertedCount++; } catch (e) { debugLog('processTextNode error:', e); } } // Process deepest containers first for (let i = containers.length - 1; i >= 0; i--) { try { if (processSplitContainer(containers[i])) convertedCount++; } catch (e) { debugLog('processSplitContainer error:', e); } } for (const sr of shadowRoots) { injectStyles(sr); observeRoot(sr); convertedCount += scanRoot(sr); } return convertedCount; } function refreshConvertedBadges() { const config = getConfig(); const d = config.decimalPlaces ?? 2; isModifying = true; try { for (const rec of activeTextRecords) { if (rec.type === 'text') { if (!rec.node || !rec.node.parentNode) { activeTextRecords.delete(rec); continue; } if (rec.mode === 'append' && rec.badge && rec.badge.isConnected && rec.matches[0]) { const formatted = formatMatchResult(rec.matches[0], d); if (formatted) { rec.badge.textContent = formatted; rec.badge.title = buildTooltip(rec.matches[0]); } } else if (rec.mode === 'replace') { let newText = rec.originalText; let offset = 0; for (const m of rec.matches) { const formatted = formatMatchResult(m, d); if (!formatted) continue; const start = m.index + offset; newText = newText.slice(0, start) + formatted + newText.slice(start + m.length); offset += formatted.length - m.length; } rec.node.nodeValue = newText; rec.replacedText = newText; } } else if (rec.type === 'group') { if (!rec.badge || !rec.badge.isConnected) { activeTextRecords.delete(rec); continue; } const formatted = formatMatchResult(rec.match, d); if (formatted) { rec.badge.textContent = formatted; rec.badge.title = buildTooltip(rec.match); } } } for (const rec of activeContainerRecords) { if (!rec.badge || !rec.badge.isConnected) { activeContainerRecords.delete(rec); continue; } const parts = rec.matches.map((m) => formatMatchResult(m, d)).filter(Boolean); if (parts.length > 0) { rec.badge.textContent = parts.join(' / '); rec.badge.title = rec.matches.map((m) => buildTooltip(m)).filter(Boolean).join(' | '); } } } finally { isModifying = false; } } function restoreAllConversions() { isModifying = true; try { for (const rec of Array.from(activeTextRecords)) { if (rec.type === 'text') { if (rec.mode === 'replace' && rec.node && rec.node.parentNode) { rec.node.nodeValue = rec.originalText; } else if (rec.mode === 'append' && rec.badge && rec.badge.parentNode) { rec.badge.parentNode.removeChild(rec.badge); } if (rec.node) textRecordMap.delete(rec.node); } else if (rec.type === 'group') { if (rec.group && rec.group.parentNode) { rec.group.parentNode.replaceChild(document.createTextNode(rec.origText), rec.group); } } } activeTextRecords.clear(); for (const rec of Array.from(activeContainerRecords)) { if (rec.hiddenEls) { for (const h of rec.hiddenEls) { if (h.classList) h.classList.remove(HIDDEN_ORIG_CLASS); } } if (rec.badge && rec.badge.parentNode) { rec.badge.parentNode.removeChild(rec.badge); } if (rec.el) containerRecordMap.delete(rec.el); } activeContainerRecords.clear(); for (const badge of Array.from(activeBadges)) { if (badge && badge.parentNode) { badge.parentNode.removeChild(badge); } } activeBadges.clear(); frozenElements = new WeakSet(); } finally { isModifying = false; } refreshFloatingPill(); } // -------------------- Incremental Scheduler & Observers -------------------- function popFirstFromSet(set) { for (const item of set) { set.delete(item); return item; } return null; } function runPendingSlice() { sliceHandle = null; const config = getConfig(); if (!config.enabled || !shouldRunOnCurrentSite()) { pendingRoots.clear(); pendingTextNodes.clear(); return; } const start = Date.now(); while (pendingTextNodes.size > 0 && (Date.now() - start) < 8) { const tn = popFirstFromSet(pendingTextNodes); if (tn && tn.isConnected) { processTextNode(tn); } } while (pendingRoots.size > 0 && (Date.now() - start) < 8) { const r = popFirstFromSet(pendingRoots); if (r && (r.isConnected || r.nodeType === 11)) { scanRoot(r); } } if (pendingTextNodes.size > 0 || pendingRoots.size > 0) { sliceHandle = setTimeout(runPendingSlice, 16); } else { refreshFloatingPill(); } } function flushPendingWork() { // If a slice loop is already running/scheduled, it will naturally drain newly added items if (sliceHandle) return; runPendingSlice(); } function scheduleIncrementalFlush(delay = 150) { clearTimeout(debounceTimer); debounceTimer = setTimeout(flushPendingWork, delay); } function findTrackedContainerAncestor(node) { let cur = node && node.nodeType === 1 ? node : (node && node.parentElement); let depth = 0; while (cur && depth < 6) { if (containerRecordMap.has(cur)) return cur; cur = cur.parentElement; depth += 1; } return null; } function observeRoot(root) { if (!root || observedRoots.has(root) || typeof MutationObserver !== 'function') return; observedRoots.add(root); const obs = new MutationObserver((muts) => { if (isModifying || !getConfig().enabled || !shouldRunOnCurrentSite()) return; let hasWork = false; for (const mut of muts) { if (mut.type === 'attributes') { const tracked = findTrackedContainerAncestor(mut.target); if (tracked) { pendingRoots.add(tracked); hasWork = true; } continue; } if (mut.type === 'characterData') { const tn = mut.target; const tracked = findTrackedContainerAncestor(tn); if (tracked) { pendingRoots.add(tracked); hasWork = true; } const parent = tn && tn.parentElement; if (parent && !isSkippedElement(parent)) { pendingTextNodes.add(tn); hasWork = true; } continue; } if (mut.type === 'childList') { const tracked = findTrackedContainerAncestor(mut.target); if (tracked) { const onlyOwnBadge = Array.from(mut.addedNodes).every( (n) => n.nodeType === 1 && n.getAttribute && n.getAttribute(PROCESSED_ATTR) === '1' ); if (!onlyOwnBadge || mut.removedNodes.length > 0) { pendingRoots.add(tracked); hasWork = true; } } for (const n of mut.addedNodes) { if (n.nodeType === 1) { if (isOwnUIElement(n) || (n.getAttribute && n.getAttribute(PROCESSED_ATTR) === '1')) { continue; } pendingRoots.add(n); hasWork = true; } else if (n.nodeType === 3 && n.nodeValue && n.nodeValue.trim().length >= 2) { const parent = n.parentElement; if (parent && !isSkippedElement(parent)) { pendingTextNodes.add(n); hasWork = true; } } } } } if (hasWork) { scheduleIncrementalFlush(150); } }); obs.observe(root, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ['aria-label'] }); } function setupSpaNavigationHooks() { if (typeof window === 'undefined' || typeof history === 'undefined') return; if (window.__ccSpaHooked) return; window.__ccSpaHooked = true; const onRouteChange = () => { yenContextCache = null; if (!getConfig().enabled || !shouldRunOnCurrentSite()) return; if (document.body) { pendingRoots.add(document.body); scheduleIncrementalFlush(200); setTimeout(() => { if (document.body && getConfig().enabled && shouldRunOnCurrentSite()) { pendingRoots.add(document.body); scheduleIncrementalFlush(100); } }, 700); } }; const origPushState = history.pushState; history.pushState = function(...args) { const ret = origPushState.apply(this, args); onRouteChange(); return ret; }; const origReplaceState = history.replaceState; history.replaceState = function(...args) { const ret = origReplaceState.apply(this, args); onRouteChange(); return ret; }; window.addEventListener('popstate', onRouteChange); } // -------------------- Site Filtering -------------------- function isUrlInList(hostname, list) { if (!hostname || !list || list.length === 0) return false; for (const rawItem of list) { const item = String(rawItem || '').trim(); if (!item) continue; const escaped = item.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*'); const regex = new RegExp('^' + escaped + '$', 'i'); if (regex.test(hostname)) return true; } return false; } function shouldRunOnCurrentSite() { const config = getConfig(); const hostname = getCurrentHostname(); if (config.listMode === 'whitelist') { return isUrlInList(hostname, config.whitelist || []); } if (config.listMode === 'blacklist') { return !isUrlInList(hostname, config.blacklist || []); } return true; } function isTopWindow() { try { return typeof window !== 'undefined' && window.self === window.top; } catch (e) { return false; } } function getConvertedCount() { let count = 0; for (const badge of activeBadges) { if (badge && badge.isConnected) count += 1; } return count; } function removeMatchingRules(hostname, list) { if (!list || list.length === 0) return []; if (!hostname) return [...list]; return list.filter((item) => !isUrlInList(hostname, [item])); } function getRootWildcardDomain(hostname) { if (!hostname) return ''; const parts = String(hostname).toLowerCase().split('.').filter(Boolean); if (parts.length <= 1) return hostname; if (parts.length === 2) return '*.' + parts.join('.'); const twoPartTlds = new Set(['co.jp', 'com.cn', 'net.cn', 'org.cn', 'co.uk', 'org.uk', 'com.hk', 'com.tw', 'com.au', 'co.kr']); const lastTwo = parts.slice(-2).join('.'); if (twoPartTlds.has(lastTwo) && parts.length >= 3) { return '*.' + parts.slice(-3).join('.'); } return '*.' + lastTwo; } function activateConversionRuntime() { const config = getConfig(); applyBadgeStyle(config.badgeStyle); if (document.body) { observeRoot(document.body); } setupSpaNavigationHooks(); setupAutoRefreshTimer(); if (config.enabled && shouldRunOnCurrentSite() && document.body) { scanRoot(document.body); } refreshFloatingPill(); } function toggleCurrentSiteFilter() { const config = getConfig(); const host = getCurrentHostname(); if (!host) return; if (config.listMode === 'whitelist') { const list = config.whitelist || []; if (isUrlInList(host, list)) { config.whitelist = removeMatchingRules(host, list); } else { config.whitelist = [...list, host]; } } else { config.listMode = 'blacklist'; const list = config.blacklist || []; if (isUrlInList(host, list)) { config.blacklist = removeMatchingRules(host, list); } else { config.blacklist = [...list, host]; } } saveConfig(config); lastAppliedConfigKey = computeConfigSyncKey(config); if (config.enabled && shouldRunOnCurrentSite()) { activateConversionRuntime(); } else { restoreAllConversions(); } registerMenuCommands(); refreshFloatingPill(); } // -------------------- Status Pill, Toast & Shadow DOM Config Panel -------------------- function computeConfigSyncKey(cfg) { return JSON.stringify([ cfg.enabled, cfg.mode, cfg.decimalPlaces, cfg.badgeStyle, cfg.yenMode, cfg.listMode, cfg.whitelist, cfg.blacklist, cfg.showStatusIndicator ]); } function showFloatingToast(message) { if (!isTopWindow() || !document.body) return; const old = document.getElementById('currency-converter-toast-host'); if (old) old.remove(); const host = document.createElement('div'); host.id = 'currency-converter-toast-host'; const shadow = host.attachShadow({ mode: 'open' }); shadow.innerHTML = `
v${escapeHtml(SCRIPT_VERSION)} · ${escapeHtml(currentHost || '未知站点')} · ${siteActive ? '已启用' : '已过滤'} · 本页已转换 ${convertedCount} 处
${ratesJson}