// ==UserScript== // @name 学习通学习助手 // @namespace https://scriptcat.org/users/王智浩 // @version 1.0.0 // @description 学习通网课辅助:倍速记忆、播完自动下一节、学习计时、逐节笔记、快捷键。不伪造进度、不自动答题,只让正常看课更省力。 // @author 王智浩 // @license MIT // @tag 学习通 // @tag chaoxing // @tag 网课 // @tag 倍速播放 // @tag 学习辅助 // @match https://*.chaoxing.com/* // @match https://mooc1.chaoxing.com/* // @match https://mooc2-ans.chaoxing.com/* // @match https://i.chaoxing.com/* // @grant GM_getValue // @grant GM_setValue // @grant GM_registerMenuCommand // @run-at document-idle // ==/UserScript== /* * ------------------------------------------------------------------ * 说明 * ------------------------------------------------------------------ * 这个脚本只做「省力」的事,不做「作弊」的事: * · 它不会伪造观看时长、不会绕开心跳/防快进、不会替你点"已完成"。 * · 它只是重设视频的 playbackRate(播放器本身的标准能力,等同于你手动拉倍速), * 外加记住你的选择、播完自动点"下一节"、暂停时提醒你、帮你记笔记。 * · 部分学校/教学点会限制倍速(超出范围会被播放器或服务端打回 1x), * 那属于课程方的设置,脚本不会也不应去破解。这类课请老实看。 * * 安装:把本文件内容全选粘贴进 ScriptCat 的编辑器,Ctrl+S 保存即可。 * ------------------------------------------------------------------ */ (function () { 'use strict'; // ============================ 配置区 ============================ const CONFIG = { // 允许的倍速范围(超出这个范围的课,播放器一般会自己打回,脚本也不硬顶) minRate: 0.25, maxRate: 4, // 倍速档位:按 ↑ / ↓ 循环切换 rateSteps: [0.75, 1, 1.25, 1.5, 1.75, 2, 2.5, 3], // "播完自动下一节" 的兜底轮询间隔(毫秒) endedPollMs: 2000, // 同一节内两次自动跳转的最小间隔,防止连环跳(毫秒) jumpCooldownMs: 5000, // 笔记自动保存延迟(毫秒) noteSaveDelayMs: 800, // 面板初始位置(px,相对于视口左上角) panelDefaultPos: { right: 16, bottom: 16 }, }; const PREFIX = 'cxh:'; // 存储 key 前缀 const TAG = '[学习助手]'; // ============================ 小工具 ============================ const log = (...a) => console.log(TAG, ...a); function fmtRate(r) { return (Math.round(r * 100) / 100).toString().replace(/\.0+$/, '') + '×'; } function clamp(n, lo, hi) { return Math.min(hi, Math.max(lo, n)); } function fmtDuration(sec) { sec = Math.max(0, Math.floor(sec)); const h = Math.floor(sec / 3600); const m = Math.floor((sec % 3600) / 60); const s = sec % 60; const pad = (x) => String(x).padStart(2, '0'); return h > 0 ? `${h}:${pad(m)}:${pad(s)}` : `${pad(m)}:${pad(s)}`; } function todayKey() { const d = new Date(); const pad = (x) => String(x).padStart(2, '0'); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; } function currentPath() { return location.host + location.pathname + location.search; } // ============================ 存储层 ============================ // 优先用 ScriptCat 的 GM_* API;没有就退回 localStorage(仍然可用,只是没有跨站同步) const store = (() => { const hasGM = typeof GM_getValue === 'function' && typeof GM_setValue === 'function'; const ls = { get(k, d) { try { const v = localStorage.getItem(PREFIX + k); return v === null ? d : JSON.parse(v); } catch (e) { return d; } }, set(k, v) { try { localStorage.setItem(PREFIX + k, JSON.stringify(v)); } catch (e) { /* 隐私模式/配额满,忽略 */ } }, }; if (hasGM) { return { get(k, d) { try { const v = GM_getValue(PREFIX + k, undefined); return v === undefined ? d : v; } catch (e) { return ls.get(k, d); } }, set(k, v) { try { GM_setValue(PREFIX + k, v); } catch (e) { ls.set(k, v); } }, kind: 'GM', }; } return { ...ls, kind: 'localStorage' }; })(); const DEFAULTS = { rate: 1, // 上次选择的倍速 autoNext: true, // 视频播完自动切下一节 muteGuard: true, // 看护:被静音/被暂停时提示并恢复 panelCollapsed: false, panelPos: null, }; const settings = new Proxy(Object.create(null), { get(_, k) { const v = store.get('cfg:' + String(k), undefined); return v === undefined ? DEFAULTS[k] : v; }, set(_, k, v) { store.set('cfg:' + String(k), v); return true; }, }); // ============================ 学习计时 ============================ const studyTimer = { last: Date.now(), started: Date.now(), start() { setInterval(() => { const now = Date.now(); const delta = Math.min(now - this.last, 5000) / 1000; this.last = now; if (document.visibilityState !== 'visible') return; // 切走/锁屏不算 this.add(delta); }, 1000); }, add(sec) { const day = store.get('study:day', ''); const cur = day === todayKey() ? store.get('study:sec', 0) : 0; store.set('study:day', todayKey()); store.set('study:sec', cur + sec); }, today() { return store.get('study:day', '') === todayKey() ? store.get('study:sec', 0) : 0; }, session() { return (Date.now() - this.started) / 1000; }, }; // ============================ 视频查找 ============================ // 学习通/智慧树的播放器常在 iframe 里,同源的话可以直接摸到,跨源就摸不到—— // 这里做一层有限的递归查找,不跨源时尽量找到真正在播的那个 video。 function collectVideos(root, depth, out) { if (depth > 3 || !root) return out; let vids = []; try { vids = root.querySelectorAll ? root.querySelectorAll('video') : []; } catch (e) { return out; } for (const v of vids) out.push(v); let frames = []; try { frames = root.querySelectorAll ? root.querySelectorAll('iframe') : []; } catch (e) { return out; } for (const f of frames) { let doc = null; try { doc = f.contentDocument; // 跨源会抛异常或返回 null } catch (e) { doc = null; } if (doc && doc.documentElement) collectVideos(doc, depth + 1, out); } return out; } // 尺寸判定需要真实布局,某些环境(无头/嵌入)拿不到,所以以样式链为准, // 尺寸只作为补充证据,避免把正常的按钮误判成"隐藏"。 function isRendered(el) { if (!el || !el.ownerDocument) return false; try { let node = el, guard = 0; while (node && node.nodeType === 1 && guard++ < 30) { const st = getComputedStyle(node); if (st.display === 'none' || st.visibility === 'hidden' || st.opacity === '0') return false; if (node === el.ownerDocument.body) break; node = node.parentElement; } return true; } catch (e) { return false; } } // 视频挑选用:优先真正占位的那个 function isVisible(el) { if (!isRendered(el)) return false; try { const r = el.getBoundingClientRect(); return r.width >= 10 && r.height >= 10; } catch (e) { return false; } } function findVideo() { const all = collectVideos(document, 0, []).filter((v) => v && v.tagName === 'VIDEO'); if (!all.length) return null; const visible = all.filter(isVisible); const pool = visible.length ? visible : all; // 优先正在播放的,其次取进度最靠后的(多集同页时基本是正确的那个) const playing = pool.find((v) => !v.paused && !v.ended); if (playing) return playing; return pool.sort((a, b) => (b.currentTime || 0) - (a.currentTime || 0))[0]; } // 等视频出现(S.P.A 路由切页时 DOM 会整块重建) // 章节页 DOM 变动极频繁,这里做节流 + 只关心"video 是否换了",避免满 CPU。 function watchVideos() { let pending = false; const tick = () => { pending = false; const v = findVideo(); if (v && v !== watchedVideo) attachVideo(v); }; const mo = new MutationObserver(() => { if (pending) return; pending = true; setTimeout(tick, 300); }); mo.observe(document.documentElement, { childList: true, subtree: true }); const v = findVideo(); if (v) attachVideo(v); } let watchedVideo = null; let lastAppliedRate = null; let lastJumpAt = 0; function applyRate(rate, v) { const video = v || findVideo(); if (!video) return false; const target = clamp(rate, CONFIG.minRate, CONFIG.maxRate); lastAppliedRate = target; try { video.defaultPlaybackRate = target; video.playbackRate = target; } catch (e) { log('设置倍速失败', e); return false; } settings.rate = target; updatePanel(); return true; } // ============================ 自动下一节 ============================ // 找"下一节"按钮:学习通章节页一般是 #prevNextFocusNext,退而求其次找文本按钮 function findNextButton() { const byId = document.querySelector('#prevNextFocusNext'); if (byId && isRendered(byId)) return byId; const texts = ['下一节', '下一课', '下一页', '下一章', '下一节 >', '下一节>']; const cands = document.querySelectorAll( 'a, button, span, div[class*="next" i], i[class*="next" i]' ); for (const el of cands) { const t = (el.textContent || '').trim(); if (!t || t.length > 10) continue; if (texts.some((x) => t === x || t.startsWith(x))) { // 排除被禁用的 if (el.closest('[disabled], .disabled, [aria-disabled="true"]')) continue; if (isRendered(el)) return el; } } // 最后:常见 class const guess = document.querySelector( '.next-btn, .nextBtn, .btn-next, [class*="nextChapter" i]' ); if (guess && isRendered(guess)) return guess; return null; } function goNext(reason) { if (!settings.autoNext) return; const now = Date.now(); if (now - lastJumpAt < CONFIG.jumpCooldownMs) return; const btn = findNextButton(); if (!btn) { toast('这一节播完了,但没找到"下一节"按钮,手动点一下吧', 'warn'); log('未找到下一节按钮,请把页面结构反馈给作者'); return; } lastJumpAt = now; log('自动下一节:', reason || ''); toast('已自动进入下一节', 'ok', 1600); btn.click(); } function attachVideo(v) { if (!v || v === watchedVideo) return; watchedVideo = v; log('已接管视频', v); // 页面一换,先恢复上次的倍速 if (settings.rate && settings.rate !== 1) applyRate(settings.rate, v); v.addEventListener('ratechange', () => { // 不是我们设的,就是用户自己改的 → 记住它 if (Math.abs(v.playbackRate - (lastAppliedRate ?? 1)) > 0.001) { lastAppliedRate = v.playbackRate; settings.rate = v.playbackRate; updatePanel(); } }); v.addEventListener('play', () => { watchedVideo = v; updatePanel(); }); v.addEventListener('ended', () => goNext('ended')); // 静音看护:有些站会在切集后把 video 静音,导致"看了个寂寞" v.addEventListener('volumechange', () => { if (!settings.muteGuard) return; if (v.muted) { setTimeout(() => { if (v.muted && settings.muteGuard) { v.muted = false; v.volume = v.volume > 0 ? v.volume : 0.6; toast('检测到视频被静音,已帮你恢复声音', 'warn'); } }, 1200); } }); updatePanel(); } // 兜底轮询:ended 事件偶尔会因为换播放器核心而不触发 function pollEnded() { setInterval(() => { if (!settings.autoNext) return; const v = findVideo(); if (!v || !isFinite(v.duration) || v.duration <= 0) return; const nearEnd = v.currentTime >= v.duration - 0.35; if ((v.ended || (nearEnd && v.paused)) && Date.now() - lastJumpAt > CONFIG.jumpCooldownMs) { goNext('poll'); } }, CONFIG.endedPollMs); } // ============================ 笔记 ============================ const note = { key() { return 'note:' + currentPath(); }, get() { return store.get(this.key(), ''); }, set(text) { store.set(this.key(), text); }, }; // ============================ UI ============================ let ui = null; // { root, rateEl, timeEl, note, noteState } function injectStyle() { const css = ` #cxh-panel{position:fixed;z-index:2147483646;right:16px;bottom:16px;width:240px; font:12px/1.5 -apple-system,"Segoe UI","Microsoft YaHei",sans-serif;color:#e6e6e6; background:rgba(24,26,30,.94);border:1px solid rgba(255,255,255,.12);border-radius:10px; box-shadow:0 8px 28px rgba(0,0,0,.45);backdrop-filter:blur(8px);user-select:none;overflow:hidden} #cxh-panel *{box-sizing:border-box} #cxh-head{display:flex;align-items:center;gap:6px;padding:7px 9px;cursor:move; background:linear-gradient(180deg,rgba(255,255,255,.07),rgba(255,255,255,0));font-weight:600} #cxh-head .dot{width:7px;height:7px;border-radius:50%;background:#4ade80;flex:0 0 auto} #cxh-head .t{flex:1 1 auto;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} #cxh-head button{all:unset;cursor:pointer;padding:0 3px;opacity:.65;font-size:13px} #cxh-head button:hover{opacity:1} #cxh-body{padding:0 9px 9px;display:grid;gap:7px} #cxh-body.hide{display:none} .cxh-row{display:flex;align-items:center;gap:6px} .cxh-row .k{opacity:.6;flex:0 0 34px} .cxh-row .v{flex:1 1 auto;font-variant-numeric:tabular-nums;font-weight:600} .cxh-btns{display:grid;grid-template-columns:repeat(4,1fr);gap:5px} .cxh-btns button{all:unset;cursor:pointer;text-align:center;padding:4px 0;border-radius:6px; background:rgba(255,255,255,.08);font-size:11px;transition:background .15s} .cxh-btns button:hover{background:rgba(255,255,255,.18)} .cxh-btns button.on{background:rgba(74,222,128,.22);color:#8ff0b0} #cxh-note{display:none;width:100%;height:74px;resize:vertical;border-radius:6px;padding:6px; border:1px solid rgba(255,255,255,.14);background:rgba(0,0,0,.35);color:#e6e6e6; font:12px/1.5 inherit;outline:none} #cxh-note.show{display:block} #cxh-tip{font-size:11px;opacity:.5} #cxh-toasts{position:fixed;z-index:2147483647;left:50%;top:14px;transform:translateX(-50%); display:grid;gap:6px;pointer-events:none} .cxh-toast{font:12px/1.5 -apple-system,"Segoe UI","Microsoft YaHei",sans-serif; padding:7px 12px;border-radius:8px;color:#fff;background:rgba(30,32,38,.95); border:1px solid rgba(255,255,255,.14);box-shadow:0 6px 20px rgba(0,0,0,.4); animation:cxh-in .18s ease-out} .cxh-toast.warn{border-color:rgba(250,204,21,.5)} .cxh-toast.ok{border-color:rgba(74,222,128,.5)} @keyframes cxh-in{from{opacity:0;transform:translateY(-6px)}to{opacity:1;transform:none}} .cxh-toast.out{opacity:0;transition:opacity .25s} `; const s = document.createElement('style'); s.textContent = css; (document.head || document.documentElement).appendChild(s); } function toast(text, kind, ms) { let box = document.getElementById('cxh-toasts'); if (!box) { box = document.createElement('div'); box.id = 'cxh-toasts'; (document.body || document.documentElement).appendChild(box); } const el = document.createElement('div'); el.className = 'cxh-toast' + (kind ? ' ' + kind : ''); el.textContent = text; box.appendChild(el); setTimeout(() => { el.classList.add('out'); setTimeout(() => el.remove(), 300); }, ms || 2400); } function buildUI() { if (ui) return ui; injectStyle(); const root = document.createElement('div'); root.id = 'cxh-panel'; root.innerHTML = `