// ==UserScript== // @name 学丞网课 · 画质记忆 // @namespace https://www.ixuecheng.cn/ // @version 1.1.0 // @description 记住学丞播放器里手动选择的画质;自动下一集或播放器重建后自动切回该画质,不再回落到"标准"(鼠标 / 触屏通用) // @author 小舟 // @match https://*.ixuecheng.cn/* // @run-at document-idle // @grant none // @noframes // ==/UserScript== /* * 原理: * 学丞的点播播放器是 xgplayer v3 + definition 插件。 * 组件里 watch 了 props.videoId,切集时会 player.destroy() 再 new Player(), * 新播放器用后端给的 defaultDefinition(通常是"标准")重建, * 所以手动选的"超清"必然丢失。 * * 本脚本不依赖任何实例引用,只做两件事: * 1) 捕获你真实点击画质菜单的动作 → 记住(localStorage) * 2) 每次播放器重建 / 视频换源后,读画质列表的选中项,与记忆不一致就点回目标项 * (直接派发事件到隐藏的 li 上,不展开菜单,无闪烁) * * 注意事件类型:xgplayer 用 'ontouchstart' in window 判断,有触摸能力就走 touch 模式, * 此时选项列表监听的是 touchend 而不是 click(手机、平板、触屏笔记本都会命中)。 * 所以派发与捕获都必须同时支持 touchend,否则触屏设备上会静默失效。 */ (function () { 'use strict'; /* ==================== 配置 ==================== */ const CFG = { // 版本号,改脚本时同步 @version version: '1.1.0', // 还没有任何记忆时的目标画质;改成 null 表示"首次不干预,只跟随用户选择" defaultQuality: '超清', // 目标画质在当前视频里不存在时,是否退而选列表第一项(通常是最高画质) fallbackToFirst: false, // 兜底轮询间隔(毫秒) tickMs: 800, // 两次点击之间的冷却(毫秒) cooldownMs: 1500, // 单集内最多尝试几次 maxRetry: 6, // 窗口限流:windowMs 内最多点击 maxInWindow 次,防止极端情况下死循环 windowMs: 10000, maxInWindow: 4, // 右下角轻提示 toast: true, // 控制台日志 debug: true, }; const STORE_KEY = 'xuecheng:quality'; const QUALITY_RE = /(超清|高清|标清|流畅|标准|蓝光|原画|4k|1080|720|540|480|hd|fhd|uhd|sd)/i; /* ==================== 工具 ==================== */ const log = (...args) => { if (CFG.debug) console.log('%c[画质记忆]', 'color:#2f7bff;font-weight:600', ...args); }; const norm = (s) => String(s == null ? '' : s).replace(/\s+/g, '').toLowerCase(); const store = { read() { try { const v = JSON.parse(localStorage.getItem(STORE_KEY) || 'null'); return v && v.name ? v : null; } catch (e) { return null; } }, write(v) { try { localStorage.setItem(STORE_KEY, JSON.stringify(v)); } catch (e) { /* 隐私模式等场景忽略 */ } }, clear() { try { localStorage.removeItem(STORE_KEY); } catch (e) {} }, }; /* ==================== 右下角提示 ==================== */ let toastEl = null; let toastTimer = 0; function toast(text) { if (!CFG.toast) return; if (!toastEl) { toastEl = document.createElement('div'); Object.assign(toastEl.style, { position: 'fixed', right: '16px', bottom: '16px', zIndex: '2147483000', padding: '8px 14px', borderRadius: '8px', fontSize: '13px', lineHeight: '18px', fontFamily: 'system-ui, "Microsoft YaHei", sans-serif', background: 'rgba(0,0,0,.78)', color: '#fff', pointerEvents: 'none', opacity: '0', transition: 'opacity .25s ease', }); (document.body || document.documentElement).appendChild(toastEl); } toastEl.textContent = text; toastEl.style.opacity = '1'; clearTimeout(toastTimer); toastTimer = setTimeout(() => { toastEl.style.opacity = '0'; }, 2200); } /* ==================== 画质菜单的 DOM 定位 ==================== */ // xgplayer 的选项列表:ul.xg-options-list,画质插件的那个 ul 带 xgplayer-definition 类, // 每项是 li.option-item,当前生效项带 selected 类,li 上还挂着 definition / url 属性。 function isQualityUl(ul) { if (!ul || !ul.querySelectorAll) return false; const items = ul.querySelectorAll('li.option-item'); if (items.length < 2) return false; if (ul.classList.contains('xgplayer-definition')) return true; if (ul.closest('.xgplayer-definition')) return true; // 兜底:全部文本都像画质名(防止类名随版本变动) let hit = 0; items.forEach((li) => { if (QUALITY_RE.test(li.textContent || '')) hit++; }); return hit === items.length; } let cachedUl = null; function getDefUl() { if (cachedUl && cachedUl.isConnected && isQualityUl(cachedUl)) return cachedUl; cachedUl = null; const uls = document.querySelectorAll('ul.xg-options-list'); for (let i = 0; i < uls.length; i++) { if (isQualityUl(uls[i])) { cachedUl = uls[i]; return cachedUl; } } return null; } function getTarget() { const saved = store.read(); if (saved) return saved; if (CFG.defaultQuality) return { name: CFG.defaultQuality, definition: '' }; return null; } function findItem(ul, want) { const items = Array.prototype.slice.call(ul.querySelectorAll('li.option-item')); const wn = norm(want.name); const wd = String(want.definition || ''); let hit = items.find((li) => norm(li.textContent) === wn); if (!hit && wd) hit = items.find((li) => (li.getAttribute('definition') || '') === wd); if (!hit && wn) hit = items.find((li) => norm(li.textContent).indexOf(wn) !== -1); return hit || null; } function currentSelected(ul) { return ul.querySelector('li.option-item.selected'); } /* ==================== 派发点击 ==================== */ let internalClick = false; function fire(el, type) { if (!el) return; const opt = { bubbles: true, cancelable: true, view: window, button: 0, detail: 1 }; internalClick = true; try { if (type === 'click') { el.dispatchEvent(new MouseEvent('click', opt)); } else if (type.indexOf('pointer') === 0 && typeof PointerEvent === 'function') { el.dispatchEvent(new PointerEvent(type, opt)); } else { el.dispatchEvent(new MouseEvent(type, opt)); } } catch (e) { /* 忽略 */ } finally { internalClick = false; } } // 触摸事件:xgplayer 在触屏设备上给选项列表绑的是 touchend,不是 click function fireTouch(el, type) { if (!el) return; internalClick = true; try { let ev; try { const touch = new Touch({ identifier: Date.now(), target: el, clientX: 0, clientY: 0, pageX: 0, pageY: 0, }); ev = new TouchEvent(type, { bubbles: true, cancelable: true, touches: [], targetTouches: [], changedTouches: [touch], }); } catch (err) { // 部分浏览器不支持 Touch 构造器,退化成普通事件(委托只认 e.target,够用) ev = new Event(type, { bubbles: true, cancelable: true }); } el.dispatchEvent(ev); } catch (e) { /* 忽略 */ } finally { internalClick = false; } } // 软模式失败后的强模式:先展开菜单,再走完整指针序列 function hardClick(root, li) { if (root) { fire(root, 'click'); fireTouch(root, 'touchend'); } setTimeout(() => { fire(li, 'pointerdown'); fire(li, 'mousedown'); fire(li, 'pointerup'); fire(li, 'mouseup'); fire(li, 'click'); fireTouch(li, 'touchend'); }, 80); } // 依次尝试「鼠标 click → 触摸 touchend → 完整指针序列 → 展开菜单再点」 // 命中即返回方式名,全都没生效返回空串 function clickItem(ul, li) { const isOn = () => { const after = currentSelected(ul); if (after === li) return true; return !!after && norm(after.textContent) === norm(li.textContent); }; fire(li, 'click'); if (isOn()) return 'click'; fireTouch(li, 'touchend'); if (isOn()) return 'touch'; fire(li, 'pointerdown'); fire(li, 'mousedown'); fire(li, 'pointerup'); fire(li, 'mouseup'); fire(li, 'click'); if (isOn()) return 'pointer'; hardClick(ul.parentElement, li); return ''; } /* ==================== 主循环 ==================== */ let lastApply = 0; let failCount = 0; let missingWarned = false; let recentClicks = []; let pendingName = ''; function rateLimited() { const now = Date.now(); recentClicks = recentClicks.filter((t) => now - t < CFG.windowMs); if (recentClicks.length >= CFG.maxInWindow) return true; recentClicks.push(now); return false; } function reset() { failCount = 0; missingWarned = false; } function tick() { const want = getTarget(); if (!want) return; const ul = getDefUl(); if (!ul) return; const hit = findItem(ul, want); const sel = currentSelected(ul); const selText = sel ? norm(sel.textContent) : ''; // 已经就是目标画质 if (hit && selText && norm(hit.textContent) === selText) { const name = (hit.textContent || '').trim(); if (pendingName && norm(pendingName) === norm(name)) { log('已切回', name); toast('画质已恢复:' + name); } pendingName = ''; reset(); return; } // 目标画质在这个视频里不存在(不同视频转码档位可能不一样) let target = hit; if (!target) { if (!CFG.fallbackToFirst) { if (!missingWarned) { missingWarned = true; log('当前视频没有「' + want.name + '」这一档,保持原样'); } return; } target = ul.querySelector('li.option-item'); if (!target) return; } missingWarned = false; if (Date.now() - lastApply < CFG.cooldownMs) return; if (failCount >= CFG.maxRetry) return; if (rateLimited()) return; lastApply = Date.now(); failCount += 1; const name = (target.textContent || '').trim(); log('切换画质 →', name, '(第 ' + failCount + ' 次)'); pendingName = name; const how = clickItem(ul, target); if (how) { log('点击已生效(' + how + ')'); schedule(600); } else { log('本轮点击都没生效,稍后重试'); } } let timer = null; function schedule(delay) { if (timer) return; timer = setTimeout(() => { timer = null; tick(); }, delay); } /* ==================== 记住用户的真实选择 ==================== */ // 触屏设备上 xgplayer 拦的是 touchend,可能不再补发 click,所以两种都要听 const onUserPick = (e) => { if (internalClick) return; const t = e.target; const li = t && t.closest ? t.closest('li.option-item') : null; if (!li) return; const ul = li.closest('ul.xg-options-list'); if (!isQualityUl(ul)) return; const name = (li.textContent || '').trim(); if (!name) return; store.write({ name: name, definition: li.getAttribute('definition') || '' }); pendingName = ''; reset(); log('记住画质:' + name); toast('已记住画质:' + name); }; ['click', 'touchend'].forEach((type) => { document.addEventListener(type, onUserPick, true); }); /* ==================== 视频换源 / 播放器重建的时机 ==================== */ const onMedia = (e) => { if (!e.target || e.target.tagName !== 'VIDEO') return; reset(); if (e.type === 'loadstart' || e.type === 'loadedmetadata' || e.type === 'canplay') { schedule(150); } }; ['loadstart', 'loadedmetadata', 'canplay', 'playing'].forEach((type) => { document.addEventListener(type, onMedia, true); }); const mo = new MutationObserver((muts) => { for (let i = 0; i < muts.length; i++) { const added = muts[i].addedNodes; for (let j = 0; j < added.length; j++) { const n = added[j]; if (!n || n.nodeType !== 1) continue; const el = n; const isPlayer = el.tagName === 'VIDEO' || (el.classList && el.classList.contains('xgplayer')) || (el.querySelector && el.querySelector('video.xgplayer, .xgplayer')) !== null; if (isPlayer) { reset(); schedule(180); return; } } } }); mo.observe(document.documentElement, { childList: true, subtree: true }); /* ==================== 启动 ==================== */ const saved = store.read(); log( 'v' + CFG.version + ' 已加载 · 记忆:' + (saved ? saved.name : '无(默认 ' + CFG.defaultQuality + ')') ); setInterval(tick, CFG.tickMs); if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => schedule(300)); } else { schedule(300); } // 控制台调试入口 window.__xuechengQuality = { cfg: CFG, get: () => store.read(), clear: () => { store.clear(); log('记忆已清除'); }, sync: () => tick(), }; })();