// ==UserScript== // @name 广工商网课助手 // @namespace https://usc.gzgs.edu.cn/ // @version 4.5.0 // @description 广工商网校刷课助手 - 原生连播驱动、强制静音、0.5~2.0 自由倍速、全功能面板可控、设置自动记忆。脚本猫/油猴双兼容,抗 SPA 样式丢失。 // @author LZKYH // @license MPL-2.0 // @match https://usc.gzgs.edu.cn/wx/study-mooc/play-vod* // @match https://usc.gzgs.edu.cn/wx/study-mooc/* // @match https://usc.gzgs.edu.cn/wx/* // @match https://usc.gzgs.edu.cn/* // @icon https://img.dxsbb.com/upFiles/infoImg/school/1944.jpg // @run-at document-idle // @grant none // @noframes // ==/UserScript== /* * 广工商网课助手 v4.5 —— 仅保留必要说明,详见各函数内注释。 * 平台要点:连播=sessionStorage['playSetScontenous']==='1'; * 倍速=AliPlayer.setSpeed 并同步 sessionStorage['playSetRate']; * 静音=video.muted + setVolume(0);进度由平台自行上报,脚本不 seek、不伪造进度。 */ (function () { 'use strict'; // ---- 单例守卫:脚本被重复注入(多管理器并存、页面内二次执行)时不重复创建面板与定时器 ---- // 注意:不能用「window 上一个布尔标记」来判重。 // 浏览器 bfcache 恢复、SPA 路由切换、页面内二次执行脚本时, // window 会保留、标记仍是 true,但 DOM 已经被换掉了 —— 结果就是 // 「标记说我在跑,实际页面里啥也没有」,用户永远看不到面板。 // 所以判重必须看 DOM 里到底有没有面板。 const INSTANCE_FLAG = '__gzhHelperV4__'; const panelId = 'gzh-panel'; const chipId = 'gzh-chip'; if (window[INSTANCE_FLAG]) { const alive = document.getElementById(panelId) || document.getElementById(chipId); if (alive) { console.log('[广工商网课助手] 检测到已有实例在运行,本次注入已跳过'); return; } // 标记残留但 DOM 已消失(bfcache/SPA 换页):清掉标记继续跑,把面板补回来 console.log('[广工商网课助手] 检测到残留标记但界面已丢失,正在重新创建'); try { delete window[INSTANCE_FLAG]; } catch (e) { window[INSTANCE_FLAG] = undefined; } } window[INSTANCE_FLAG] = true; // ============================ 设置持久化 ============================ const SETTINGS_KEY = 'gzh_helper_settings_v4'; // 默认设置(首装 / 重置时使用) const DEFAULTS = { // —— 播放控制 —— // autoPlayNext 已改为内置恒定行为(不暴露到面板、不参与设置), // 见 ensureContinuousPlay()。老配置里的该字段会被 loadSettings 忽略。 autoResume: true, // 意外暂停自动恢复 forceMute: false, // 强制静音 rateEnabled: true, // 倍速调控总开关(关则恢复 1.0) rate: 1.0, // 当前倍速 0.5 ~ 2.0 // —— 辅助功能 —— autoConfirmVerify: true, // 自动确认人机验证 autoNextFallback: true, // 连播兜底(平台没自动切时主动点下一节) keepScreenWake: false, // 保持屏幕常亮(防笔记本息屏暂停) // —— 面板 —— // 面板是否显示:默认 true。 // v4.2 初版这里会忠实读回上次存的 false,结果用户一关闭就再也看不到面板; // 现在 init 里对 false 的情况会补建「助手」胶囊作为入口,不会再失联。 panelVisible: true, // 注意:折叠状态(collapsed)刻意不做持久化,只保存在 STATE 里。 // 折叠是临时动作,记住它只会让下次打开时找不到面板。 panelPos: null, // {left, top} 或 null=默认右下角 // 设置结构版本。v4.2 起:小于此值的旧记录会被做一次一次性修正 confVer: 2, // —— 内部 —— stallThreshold: 20000, // 暂停多久算卡住(ms) reloadStallThreshold: 180000 }; // 把最终设置持久化(loadSettings 内使用,此时 SETTINGS 尚未定义) function persist(obj) { try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(obj)); } catch (e) { /* 配额满等,忽略 */ } return obj; } function loadSettings() { let out; // 原始记录是否自带 confVer —— 必须在合并前判断, // 否则 DEFAULTS 里的 confVer:2 会把"老数据没有该字段"掩盖成"已是新版"。 let rawConfVer = 0; try { const raw = localStorage.getItem(SETTINGS_KEY); // 无记录:首装,写入默认值 if (!raw) return persist(Object.assign({}, DEFAULTS)); const obj = JSON.parse(raw); // 非对象(字符串/数字/null/数组):视为损坏 if (!obj || typeof obj !== 'object' || Array.isArray(obj)) { return persist(Object.assign({}, DEFAULTS)); } rawConfVer = Number(obj.confVer) || 0; // 合并:仅接受 DEFAULTS 中存在的键,类型不符则保留默认值 out = Object.assign({}, DEFAULTS); for (const k of Object.keys(DEFAULTS)) { if (!(k in obj)) continue; const dv = DEFAULTS[k]; const ov = obj[k]; if (dv === null) { out[k] = ov; continue; } // panelPos 等可为 null if (typeof ov === typeof dv) out[k] = ov; else if (k === 'rate' && typeof ov === 'number' && isFinite(ov)) out[k] = ov; } } catch (e) { // JSON 解析失败等:回落默认值 out = Object.assign({}, DEFAULTS); } // 倍速范围纠正 out.rate = clampRate(out.rate); // 一次性修正:老版本(confVer 缺失或 < 2)可能存了 panelVisible:false, // 那是删快捷键后「关闭即失联」的残留状态,强制恢复为显示。 // 从 v4.2 之后用户再主动关闭就正常记住,不再被这里覆盖。 if (rawConfVer < 2) { out.panelVisible = true; out.confVer = 2; } // 立即回写:把纠正后的值持久化,避免脏值在下次启动时被当作合法值反复读取 return persist(out); } function saveSettings() { try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(SETTINGS)); } catch (e) { /* 配额满等,忽略 */ } } function clampRate(r) { const n = Number(r); if (!isFinite(n)) return 1.0; // 0.5 ~ 2.0,步进 0.05 return Math.min(2.0, Math.max(0.5, Math.round(n * 20) / 20)); } const SETTINGS = loadSettings(); // 兼容旧字段名(v3 用 CONFIG.* 的地方统一改走 SETTINGS,这里保留别名便于阅读) const CONFIG = SETTINGS; // ============================ 状态 ============================ const STATE = { timers: [], userPaused: false, resuming: false, lastResumeAt: 0, // 上次尝试恢复播放的时间(退避用) resumeFailCount: 0, // 连续恢复失败次数 lastResumeAt: 0, // 上次尝试恢复播放的时间(退避用) resumeFailCount: 0, // 连续恢复失败次数 internalPause: false, pauseSince: null, startedAt: 0, currentChapterId: null, currentTitle: '', catalog: [], doneCount: 0, totalCount: 0, lastTime: 0, lastTimeAt: 0, lastReloadAt: 0, video: null, boundVideo: null, player: null, // AliPlayer 组件实例 boundPlayer: null, playerMissAt: 0, // 上次查找播放器失败的时间(用于退避重试) playerMissAt: 0, // 上次查找播放器失败的时间(用于退避重试) phase: 'idle', // idle | playing | paused | ended sawVideo: false, hidden: false, // 平台倍速上限(教师设置),来自 vodParams.multiple courseRateLimit: null, // 上次应用的静音状态(避免每 tick 重复写) appliedMute: null, appliedRate: null, // 连播兜底计时 endedAt: 0, fallbackDone: false, panel: null, collapsed: false, // 折叠状态:仅本次会话有效,不写入 localStorage logs: [], logDirty: false, // 日志有更新但面板没展开,待渲染 wakeLock: null, // 重置按钮的二次确认标记(第一次点击置 true,3 秒后撤销) resetArmed: false }; const LOG_LEVELS = { INFO: 'info', OK: 'ok', WARN: 'warn', ERR: 'err' }; // ============================ 日志 ============================ // 三条规则,避免日志变成刷屏垃圾: // 1) 同名消息 1.5 秒内合并成一条,只把计数累加上去(显示 ×N) // 2) 全部最多保留 120 条 // 3) 面板收起时不做 DOM 渲染,展开时一次画完 const LOG_MAX = 120; const LOG_DEDUPE_MS = 1500; function nowStr() { const t = new Date(); return `${String(t.getHours()).padStart(2, '0')}:${String(t.getMinutes()).padStart(2, '0')}:${String(t.getSeconds()).padStart(2, '0')}`; } function log(msg, level = LOG_LEVELS.INFO) { const now = Date.now(); const last = STATE.logs[0]; // 同一条消息连发 → 只累加计数,不新增一行 if (last && last.msg === msg && last.level === level && now - last.at < LOG_DEDUPE_MS) { last.at = now; last.count = (last.count || 1) + 1; last.ts = nowStr(); // 计数变化也要重画,否则界面会一直停在 ×1 renderPanelLog(); return; } STATE.logs.unshift({ ts: nowStr(), at: now, level, msg, count: 1 }); if (STATE.logs.length > LOG_MAX) STATE.logs.length = LOG_MAX; STATE.logDirty = true; // console 只留 WARN/ERR 便于排查,日常 INFO 不刷控制台 if (level !== LOG_LEVELS.INFO) { const fn = level === LOG_LEVELS.ERR ? console.error : console.warn; fn(`[广工商网课助手] ${msg}`); } renderPanelLog(); } function clearLogs() { STATE.logs.length = 0; STATE.logDirty = true; renderPanelLog(); } // ============================ 工具 ============================ function $(sel, ctx = document) { return ctx.querySelector(sel); } function $$(sel, ctx = document) { return Array.prototype.slice.call(ctx.querySelectorAll(sel)); } function textOf(el) { if (!el) return ''; const t = (el.textContent != null ? el.textContent : el.innerText); return t == null ? '' : String(t); } function isVisible(el) { if (!el) return false; if (el.tagName === 'BODY') return true; // 注意:offsetParent 在 position:fixed 和部分容器下天然为 null,不能作为主判据; // 以 computedStyle + 祖先链为准,避免误杀真实可见的弹窗。 const st = window.getComputedStyle(el); if (st.display === 'none' || st.visibility === 'hidden') return false; const op = Number(st.opacity); if (isFinite(op) && op <= 0.01) return false; // display:none 的祖先会让后代一起不可见,逐级向上确认 let node = el.parentElement; let guard = 0; while (node && guard < 20) { const ps = window.getComputedStyle(node); if (ps.display === 'none' || ps.visibility === 'hidden') return false; node = node.parentElement; guard++; } return true; } function realClick(el) { if (!el) return false; try { el.dispatchEvent(new MouseEvent('click', { view: window, bubbles: true, cancelable: true, button: 0 })); return true; } catch (e) { try { el.click(); return true; } catch (e2) { return false; } } } function fmtDuration(sec) { if (!isFinite(sec) || sec < 0) return '--:--'; const h = Math.floor(sec / 3600); const m = Math.floor((sec % 3600) / 60); const s = Math.floor(sec % 60); if (h > 0) return `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`; return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`; } const SS = { get(k, def) { try { const v = sessionStorage.getItem(k); return v == null ? def : v; } catch (e) { return def; } }, set(k, v) { try { sessionStorage.setItem(k, v); } catch (e) { /* 忽略 */ } } }; // ============================ 播放器实例 ============================ // 通过 DOM 上的 __vue__ 反查 AliPlayer 组件实例,用于调用 setSpeed / setVolume function findPlayer() { // 已知容器类名 const sel = ['.aliplayer-vod-wrap', '.prism-player', '.aliplayer', '[class*="aliplayer"]']; for (const s of sel) { const els = $$(s); for (const el of els) { let node = el; let depth = 0; while (node && depth < 6) { const vm = node.__vue__; if (vm) { // 自身或 $refs 里含 videoAliplayer if (vm.$refs && vm.$refs.videoAliplayer && typeof vm.$refs.videoAliplayer.setSpeed === 'function') { return vm.$refs.videoAliplayer; } if (typeof vm.setSpeed === 'function' && typeof vm.getCurrentTime === 'function') { return vm; } } node = node.parentElement; depth++; } } } // 兜底:遍历所有带 __vue__ 的元素找 $refs.videoAliplayer const all = $$('*'); for (const el of all) { const vm = el.__vue__; if (vm && vm.$refs && vm.$refs.videoAliplayer && typeof vm.$refs.videoAliplayer.setSpeed === 'function') { return vm.$refs.videoAliplayer; } } return null; } function getPlayer() { // 缓存的实例失效时重新查找 if (STATE.player && typeof STATE.player.setSpeed === 'function') return STATE.player; const now = Date.now(); // 查找失败会退化成 $$('*') 全量遍历,页面很大时开销高。 // 失败后 10 秒内不再重试,避免每 tick 都全量扫描拖慢播放页。 if (now - STATE.playerMissAt < 10000) return null; const p = findPlayer(); if (p) { STATE.player = p; STATE.boundPlayer = p; STATE.playerMissAt = 0; } else { STATE.playerMissAt = now; } return p; } // ============================ 连播开关 ============================ // 自动连播是内置恒定行为:不暴露到面板,也刻意不给关闭入口。 // 依据:sessionStorage['playSetScontenous'] === '1' 是平台自己的连播标志, // 让平台原生逻辑接管比自实现连播稳得多(不会重复触发、不会跳节)。 function ensureContinuousPlay() { if (SS.get('playSetScontenous') !== '1') { SS.set('playSetScontenous', '1'); } } function syncAutoPlaySwitch() { const switches = $$('.contenuous-right .el-switch'); for (const sw of switches) { if (!isVisible(sw)) continue; const wrap = sw.closest('.contenuous-right') || sw.parentElement; if (!/自动连播/.test(textOf(wrap))) continue; if (sw.classList.contains('is-checked')) return; const core = sw.querySelector('.el-switch__core') || sw; realClick(core); log('已同步页面「自动连播」开关', LOG_LEVELS.OK); return; } } // ============================ 视频元素 ============================ function findVideo() { const own = $$('video'); if (own.length) return own[0]; for (const f of $$('iframe')) { try { const doc = f.contentDocument; if (!doc) continue; const v = doc.querySelector('video'); if (v) return v; } catch (e) { /* 跨域 */ } } return null; } function bindVideo(v) { if (!v || STATE.boundVideo === v) return; STATE.boundVideo = v; STATE.video = v; STATE.sawVideo = true; // 新视频元素:重置已应用标记,让下一 tick 重新施加静音/倍速 STATE.appliedMute = null; STATE.appliedRate = null; STATE.endedAt = 0; STATE.fallbackDone = false; v.addEventListener('play', () => { STATE.userPaused = false; STATE.phase = 'playing'; STATE.lastTime = v.currentTime; STATE.lastTimeAt = Date.now(); STATE.appliedMute = null; // 重新施加 STATE.appliedRate = null; // 平台切集 / 恢复播放会把音量、倍速打回默认,必须立刻重施, // 不能等下一个 tick(tick 2s 一次,会漏掉可感知的一小段)。 applyVideoSettings(true); }); v.addEventListener('pause', () => { if (STATE.internalPause) { STATE.phase = 'paused'; return; } if (!v.ended) { STATE.userPaused = true; STATE.phase = 'paused'; log('视频已暂停', LOG_LEVELS.WARN); } }); v.addEventListener('ended', () => { STATE.phase = 'ended'; STATE.endedAt = Date.now(); STATE.fallbackDone = false; log('本节播放结束,等待平台自动连播…', LOG_LEVELS.OK); }); v.addEventListener('error', () => { log('视频元素报错', LOG_LEVELS.ERR); }); v.addEventListener('timeupdate', () => { STATE.lastTime = v.currentTime; STATE.lastTimeAt = Date.now(); STATE.phase = 'playing'; }); } // ============================ 静音 / 倍速 ============================ // 强制静音:muted 属性 + 音量置 0 双保险。 // 平台 volumeFunction 只在开始/结束播放时按 vodSetting.volume 调 setVolume, // 播放中途不会重置,因此可稳定保持。 function applyMute(force) { const v = findVideo(); if (!v) return; if (STATE.boundVideo !== v) bindVideo(v); const want = !!SETTINGS.forceMute; // 若状态未变且不是强制施加,跳过(省开销) if (!force && STATE.appliedMute === want && v.muted === want) return; try { v.muted = want; } catch (e) { /* 忽略 */ } // 音量也一并处理:音量 0 比 muted 更难被播放器内部逻辑覆盖 const p = getPlayer(); try { if (p && typeof p.setVolume === 'function') { if (want) { p.setVolume(0); } else { // 恢复:优先用平台记录的音量 let vol = 0.5; try { const s = JSON.parse(localStorage.getItem('vodSetting') || '{}'); if (s && typeof s.volume === 'number' && s.volume > 0) vol = s.volume; } catch (e) { /* 忽略 */ } p.setVolume(vol); } } } catch (e) { /* 忽略 */ } if (!want) { // 关闭静音时确保原生音量不为 0 if (v.volume === 0) { try { v.volume = 0.5; } catch (e) { /* 忽略 */ } } } STATE.appliedMute = want; // 只在用户主动切换时记一条,tick 里的重复施加不刷屏 if (force) log(want ? '已开启强制静音' : '已关闭强制静音', LOG_LEVELS.OK); } // 倍速:优先 AliPlayer.setSpeed(组件内部状态会同步),回退原生 playbackRate。 // 同时写入 sessionStorage.playSetRate,使平台在切集/刷新后恢复为同一倍速。 function applyRate(force) { const v = findVideo(); if (!v) return; if (STATE.boundVideo !== v) bindVideo(v); const want = SETTINGS.rateEnabled ? clampRate(SETTINGS.rate) : 1.0; if (!force && STATE.appliedRate === want && Math.abs((v.playbackRate || 1) - want) < 0.001) return; let ok = false; const p = getPlayer(); if (p && typeof p.setSpeed === 'function') { try { p.setSpeed(String(want)); ok = true; } catch (e) { /* 回退 */ } } // 无论 setSpeed 是否成功,都直接设置原生倍速作为保障 try { v.playbackRate = want; if (Math.abs(v.playbackRate - want) < 0.001) ok = true; } catch (e) { // 部分浏览器对某些倍速会抛错(如 <0.25 或 >16) } // 同步平台的倍速记录,保证切集后不被平台重置 SS.set('playSetRate', String(want)); STATE.appliedRate = want; // 成功不写日志——面板上的倍速数字本身就是反馈;失败才值得记一条 if (!ok) log(`倍速设置未生效(${want.toFixed(2)}×)`, LOG_LEVELS.WARN); } function applyVideoSettings(force) { applyMute(force); applyRate(force); } // ============================ 平台状态读取 ============================ function getVueHostComponent() { const roots = $$('.aliplayer-vod-wrap'); for (const r of roots) { let node = r; let d = 0; while (node && d < 6) { const vm = node.__vue__; if (vm && vm.vodParams) return vm; node = node.parentElement; d++; } } return null; } function readPlatformState() { const vm = getVueHostComponent(); if (!vm) return null; return { vodParams: vm.vodParams || {}, chapterListData: vm.chapterListData || [], flagSectionArr: vm.flagSectionArr || [], iScontenuousPlay: vm.iScontenuousPlay, chapterStudyRecordId: vm.chapterStudyRecordId, playNumber: vm.playNumber || {} }; } // 读取本课程倍速上限(教师设置 vodParams.multiple) function readCourseRateLimit() { const st = readPlatformState(); if (!st) return null; const m = Number(st.vodParams.multiple); if (isFinite(m) && m > 0) return m; return null; } // ============================ 恢复播放 ============================ function resumePlayback(reason) { const v = STATE.boundVideo; if (!v || v.ended || !v.paused) return; if (STATE.resuming || !SETTINGS.autoResume) return; // 退避:连续恢复失败时逐次拉长间隔,避免在无解场景(片源出错、已播完 // 但 ended 属性未置位)里每 20 秒刷一次日志、反复打断用户。 const now = Date.now(); const sinceLast = now - (STATE.lastResumeAt || 0); const needGap = Math.min(300000, 15000 * Math.pow(2, STATE.resumeFailCount || 0)); if (sinceLast < needGap) return; STATE.lastResumeAt = now; STATE.resuming = true; // 不单独记「正在尝试」,成功/失败时各记一条就够 const prevMuted = v.muted; // 静音状态下 play() 不会被自动播放策略拦截 try { v.muted = true; } catch (e) { /* 忽略 */ } let p; try { p = v.play(); } catch (e) { STATE.resuming = false; STATE.resumeFailCount = (STATE.resumeFailCount || 0) + 1; clickBigPlayButton(); return; } const done = () => { STATE.resuming = false; STATE.userPaused = false; STATE.phase = 'playing'; STATE.lastTime = v.currentTime; STATE.lastTimeAt = Date.now(); // 恢复用户原本的静音设置 try { v.muted = SETTINGS.forceMute ? true : prevMuted; } catch (e) { /* 忽略 */ } STATE.appliedMute = null; STATE.appliedRate = null; // 播放位置确实推进了才算真正恢复成功,否则累加失败计数 setTimeout(() => { if (!v.paused && !v.ended) { STATE.resumeFailCount = 0; log(`已恢复播放(${reason})`, LOG_LEVELS.OK); } else { STATE.resumeFailCount = (STATE.resumeFailCount || 0) + 1; if (STATE.resumeFailCount >= 3) { log('多次恢复未成功,已暂停自动恢复尝试', LOG_LEVELS.WARN); } } }, 1500); }; if (p && typeof p.then === 'function') { p.then(done).catch(() => { STATE.resuming = false; STATE.resumeFailCount = (STATE.resumeFailCount || 0) + 1; clickBigPlayButton(); }); } else { setTimeout(done, 300); } } function clickBigPlayButton() { const cands = [ '.prism-big-play', '.vjs-big-play-button', '.aliplayer-ctr-play', '.aliplayer-icon-play', '.play-btn', '[class*="big-play"]', '.prism-controlbar .icon-play' ]; for (const sel of cands) { const el = $(sel); if (el && isVisible(el)) { realClick(el); log('已点击播放器播放按钮', LOG_LEVELS.INFO); return; } } } // ============================ 真人验证 ============================ function handleVerifyDialog() { if (!SETTINGS.autoConfirmVerify) return; for (const box of $$('.el-message-box')) { if (!isVisible(box)) continue; const text = textOf(box); if (!/验证|真人观看|继续播放|确认|拖动|学习/.test(text)) continue; const btns = $$('.el-message-box__btns button', box); for (const b of btns) { const label = textOf(b).trim(); if (/^(确定|确认|好的|继续播放|知道了)$/.test(label)) { realClick(b); STATE.internalPause = false; setTimeout(() => { STATE.userPaused = false; resumePlayback('验证弹窗确认后'); }, 300); log('已自动确认人机验证弹窗', LOG_LEVELS.OK); return; } } } if (STATE.phase === 'paused' && !STATE.userPaused && !STATE.internalPause) { resumePlayback('检测到未恢复的暂停'); } } // ============================ 目录读取 ============================ function readCatalog() { const items = $$('.course-chapter-item'); if (!items.length) return null; const list = []; for (const el of items) { const titleEl = el.querySelector('.course-chapter-item-text'); const subEl = el.querySelector('.sub-chapter'); const subLabel = subEl ? textOf(subEl).trim() : ''; let title = titleEl ? textOf(titleEl).trim().replace(/\s+/g, ' ') : ''; if (title) { const stripped = title.replace(/^(必修|选修)\s*/, '').trim(); if (stripped) title = stripped; } const finished = el.classList.contains('had-finished'); const active = el.classList.contains('actived'); const canPlay = el.classList.contains('can-play'); let pct = null; const prog = el.querySelector('.detail-progress'); if (prog) { const m = textOf(prog).match(/(\d+)\s*%/); if (m) pct = parseInt(m[1], 10); else { const raw = textOf(prog).trim(); if (/^\d+$/.test(raw)) pct = parseInt(raw, 10); } } list.push({ el, title, subLabel, finished, active, canPlay, pct }); } STATE.catalog = list; STATE.doneCount = list.filter(s => s.finished).length; STATE.totalCount = list.length; const activeItem = list.find(s => s.active); if (activeItem) { STATE.currentTitle = activeItem.subLabel ? `${activeItem.subLabel} ${activeItem.title}` : activeItem.title; } return list; } // ============================ 连播兜底 ============================ // 平台原生连播若未触发(例如 playSetScontenous 被重置、或平台逻辑异常), // 在结束后等待若干秒仍无新播放,则主动点下一节。 function checkAutoNextFallback() { if (!SETTINGS.autoNextFallback) return; if (STATE.phase !== 'ended' || STATE.fallbackDone) return; if (!STATE.endedAt) return; const waited = Date.now() - STATE.endedAt; if (waited < 12000) return; // 若视频已重新开始播放或已切集,说明平台连播成功 const v = STATE.boundVideo; if (v && !v.ended && !v.paused) { STATE.fallbackDone = true; return; } STATE.fallbackDone = true; log('平台未自动切换,执行兜底连播', LOG_LEVELS.WARN); goNextSection(false); } // ============================ 主循环 ============================ let tickCount = 0; function tick() { if (STATE.hidden) return; tickCount++; const v = findVideo(); if (v && STATE.boundVideo !== v) bindVideo(v); // 每 tick 保持静音/倍速(轻量:状态未变则内部直接 return) if (STATE.boundVideo) applyVideoSettings(false); if (tickCount % 10 === 0) { ensureContinuousPlay(); syncAutoPlaySwitch(); // 定期校准倍速上限 const lim = readCourseRateLimit(); if (lim != null) STATE.courseRateLimit = lim; } if (tickCount % 2 === 0) handleVerifyDialog(); readCatalog(); updatePanelStatus(); checkStall(); checkAutoNextFallback(); } function checkStall() { const v = STATE.boundVideo; if (!v) return; const now = Date.now(); if (v.paused && !v.ended && !STATE.userPaused && !STATE.internalPause) { if (STATE.pauseSince == null) STATE.pauseSince = now; else if (now - STATE.pauseSince > SETTINGS.stallThreshold) { STATE.pauseSince = now; resumePlayback('长时间暂停'); } } else { STATE.pauseSince = null; } if (!v.paused && !v.ended && STATE.lastTimeAt) { if (now - STATE.lastTimeAt > SETTINGS.reloadStallThreshold) { log('播放进度长时间未推进,重新加载', LOG_LEVELS.WARN); safeReload('播放停滞'); return; } } } function safeReload(reason) { const now = Date.now(); if (now - STATE.lastReloadAt < 90000) { log('距上次重载不足 90 秒,跳过', LOG_LEVELS.WARN); return; } STATE.lastReloadAt = now; log(`页面重载:${reason}`, LOG_LEVELS.WARN); setTimeout(() => location.reload(), 800); } // ============================ 屏幕常亮 ============================ async function setWakeLock(on) { try { if (on) { if (!('wakeLock' in navigator)) { log('当前浏览器不支持屏幕常亮', LOG_LEVELS.WARN); SETTINGS.keepScreenWake = false; saveSettings(); syncPanelControls(); return; } if (STATE.wakeLock) return; STATE.wakeLock = await navigator.wakeLock.request('screen'); STATE.wakeLock.addEventListener('release', () => { STATE.wakeLock = null; }); log('屏幕常亮:已开启', LOG_LEVELS.OK); } else { if (STATE.wakeLock) { await STATE.wakeLock.release(); STATE.wakeLock = null; } log('屏幕常亮:已关闭', LOG_LEVELS.OK); } } catch (e) { log('屏幕常亮设置失败:' + (e && e.message ? e.message : e), LOG_LEVELS.WARN); } } // ============================ 面板 UI ============================ // 挂载策略:优先挂到 下的独立根容器,而不是直接塞进 body。 // 两个原因: // 1) document.body 在极早期可能还不存在(Nuxt 页面、bfcache 恢复、 // 某些扩展的注入时机),直接 appendChild 会抛 TypeError, // 一旦抛出来整个 init 就断了,用户什么都看不到。 // 2) 平台的 #__nuxt 容器如果带 transform,会创建一个新的层叠上下文, // 挂在它内部的 position:fixed 元素会相对于该容器定位而不是视口, // 结果就是面板被定位到屏幕外 —— 肉眼看起来就是"没显示"。 // 独立根容器不继承任何 transform,position:fixed 永远相对视口。 const MOUNT_ID = 'gzh-root'; function mountToBody(el) { let root = document.getElementById(MOUNT_ID); if (!root) { root = document.createElement('div'); root.id = MOUNT_ID; // 根容器本身不能有 transform / filter / perspective / contain / will-change, // 任何一个都会给它造出层叠上下文,让子元素的 position:fixed 失效。 root.style.cssText = [ 'position:static', 'display:block', 'width:0', 'height:0', 'margin:0', 'padding:0', 'border:0', 'overflow:visible', 'transform:none', 'filter:none', 'perspective:none', 'contain:none', 'will-change:auto', 'backdrop-filter:none', 'opacity:1', 'visibility:visible', 'pointer-events:none' ].join(';') + ';'; const host = document.documentElement || document.body; if (!host) return false; host.appendChild(root); } // style 也挂进根容器,不进 document.head —— Nuxt 水合/路由切换会重写
, // 把 head 里的