// ==UserScript== // @name 虎牙直播间净化助手 // @namespace https://www.huya.com/ // @version 1.3.1 // @description 自动最高画质(免登录解锁蓝光)+ 自动跳过直播间广告(含顶部通栏/右侧小屏/左下角扫码浮层)+ 屏蔽自动弹出登录框 // @author Little Code Sauce // @license MIT // @match *://www.huya.com/* // @run-at document-start // @grant GM_getValue // @grant GM_setValue // @grant GM_registerMenuCommand // @grant GM_addStyle // @grant unsafeWindow // ==/UserScript== (function () { 'use strict'; /* ================================================================== * * 三条独立能力线: * A. 自动跳过广告 频次配额预置(document-start)+ MutationObserver + 运行时清扫 * 含三处常驻广告位:顶部通栏 / 右侧小屏 / 左下扫码浮层 * B. 自动最高画质 解锁 "请先登录" 档位后自动切到最高档 * C. 屏蔽登录弹窗 配额顶满 + 门控,且不挡用户主动登录 * ================================================================== */ // 页面真实 window —— 必须用它取 jQuery,否则拿不到页面数据 var PAGE = (function () { try { return (typeof unsafeWindow !== 'undefined' && unsafeWindow) ? unsafeWindow : window; } catch (e) { return window; } })(); var TAG = '[虎牙净化] '; function log() { try { console.log.apply(console, [TAG].concat([].slice.call(arguments))); } catch (e) {} } var opt = { autoBestQuality: GM_getValue('hy_auto_quality', true), skipAd: GM_getValue('hy_skip_ad', true), blockLoginPopup: GM_getValue('hy_block_login', true) }; function persist() { GM_setValue('hy_auto_quality', opt.autoBestQuality); GM_setValue('hy_skip_ad', opt.skipAd); GM_setValue('hy_block_login', opt.blockLoginPopup); } [['autoBestQuality', '自动最高画质'], ['skipAd', '自动跳过广告'], ['blockLoginPopup', '屏蔽自动登录框'] ].forEach(function (it) { GM_registerMenuCommand((opt[it[0]] ? '✅ ' : '⬜ ') + it[1], function () { opt[it[0]] = !opt[it[0]]; persist(); location.reload(); }); }); var DIAG = { steps: [], unlocked: 0, clicked: 0, switched: false, topAd: 0, sideAd: 0, shAd: 0 }; function mark(s) { if (DIAG.steps.length < 60) DIAG.steps.push(s); } function todayKey() { var d = new Date(); return d.getFullYear() + '/' + (d.getMonth() + 1) + '/' + d.getDate(); } function readJSON(key, fb) { try { var v = JSON.parse(localStorage.getItem(key) || 'null'); return (v && typeof v === 'object') ? v : fb; } catch (e) { return fb; } } /* ------------------------------------------------------------------ * * 一、document-start 预置(必须早于页面 vplayer.js) * 页面的广告判定在 VPlayer 构造函数里同步完成,晚一步就无效。 * ------------------------------------------------------------------ */ (function plantAdQuota() { if (!opt.skipAd) return; try { var ab = readJSON('abConfig', {}); if (!ab.mpConfig || typeof ab.mpConfig !== 'object') ab.mpConfig = {}; var zero = JSON.stringify({ gidCfgList: [{ gameid: '-1', count: '0', interval: '1' }] }); ab.mpConfig.preAdFrequency = zero; ab.mpConfig.replayPreAdFrequency = zero; ab.mpConfig.preadShowTime = '1'; localStorage.setItem('abConfig', JSON.stringify(ab)); // vplayer 自带豁免:当日 failCount > 2 时广告判定直接 return。 // 它每天首次访问会把 failCount 归零,所以每天重新顶满。 var ps = readJSON('preadShow', {}); ps.showDate = todayKey(); ps.failCount = 99; ps.success = 0; ps.replaySuccess = 0; ps.lastShowTime = 0; localStorage.setItem('preadShow', JSON.stringify(ps)); mark('ad-quota-ok'); } catch (e) { mark('ad-quota-err'); log('plantAdQuota', e); } })(); (function plantLoginQuota() { if (!opt.blockLoginPopup) return; try { var lf = readJSON('LOGIN_FORCE_TIME', {}); var t = todayKey(); if (parseInt(lf[t], 10) < 999) { lf[t] = 999; localStorage.setItem('LOGIN_FORCE_TIME', JSON.stringify(lf)); } mark('login-quota-ok'); } catch (e) { mark('login-quota-err'); log('plantLoginQuota', e); } })(); /* ------------------------------------------------------------------ * * 二、样式层 * ------------------------------------------------------------------ */ var CSS = [ 'html.hy-no-login #HUYA-UDBSdkLgn,', 'html.hy-no-login #UDBSdkLgn-mask { display: none !important; }', 'html.hy-no-login body[style*="overflow"] { overflow: auto !important; position: static !important; }', '#player-login-guide-tip, #player-login-tip { display: none !important; }', '#pre-ab-video.new-pre-ab-video { display: none !important; }', // 三处常驻广告位 '#J_roomGgTop, .room-gg-top { display: none !important; }', '#public-screen-ab, #ab-banner { display: none !important; }', '.small-handle-tip, .player-smallhandle-panel,', '.player-smallhandle-big-image { display: none !important; }', '.player-gift-left .ab-icon.xsb-icon { display: none !important; }', // 顶部通栏是普通流内元素,display:none 后自然不占位,无需改父容器 '#J_roomGgTop { height: 0 !important; margin: 0 !important; padding: 0 !important; }' ].join('\n'); try { GM_addStyle(CSS); } catch (e) { var st = document.createElement('style'); st.textContent = CSS; (document.head || document.documentElement).appendChild(st); } /* ------------------------------------------------------------------ * * 三、登录弹窗门控 * 区分自动弹窗与主动登录:真实输入(isTrusted)后 5 秒内出现的 * 登录框视为用户自己打开的,此后本次会话不再干预。 * ------------------------------------------------------------------ */ (function loginGate() { if (!opt.blockLoginPopup) return; var lastInput = 0, userOpened = false; ['pointerdown', 'mousedown', 'touchstart', 'keydown'].forEach(function (ev) { window.addEventListener(ev, function (e) { if (e && e.isTrusted !== false) lastInput = Date.now(); }, true); }); function boxHasContent() { var el = document.getElementById('HUYA-UDBSdkLgn'); if (!el) return false; var box = document.getElementById('UDBSdkLgn-box'); return !!(box && box.innerHTML.replace(/\s/g, '') !== ''); } function sync() { var html = document.documentElement; if (userOpened) { html.classList.remove('hy-no-login'); return; } if (boxHasContent() && Date.now() - lastInput < 5000) { userOpened = true; html.classList.remove('hy-no-login'); mark('user-login-allowed'); return; } if (boxHasContent()) { var el = document.getElementById('HUYA-UDBSdkLgn'); el.style.display = 'none'; var box = document.getElementById('UDBSdkLgn-box'); if (box) box.innerHTML = ''; if (document.body && document.body.style.overflow) { document.body.style.overflow = ''; document.body.style.position = ''; } mark('auto-login-blocked'); } html.classList.add('hy-no-login'); } sync(); setInterval(sync, 400); })(); /* ------------------------------------------------------------------ * * 四、广告运行时清扫 * ------------------------------------------------------------------ */ var AD_MEDIA_RE = /adsmind\.gdtimg\.com|ads_svp_video|gdtimg\.com/i; var AD_FRAME_RE = /zt\.huya\.com|ad\.huya\.com|adsmind|gdtimg/i; // 三处常驻广告位的静态选择器 var AD_SLOT_SEL = [ '#J_roomGgTop', '.room-gg-top', '.room-mod-ggTop', // 顶部通栏 '#public-screen-ab', '#ab-banner', // 右侧栏小屏 '.small-handle-tip', '.player-smallhandle-panel', // 左下角扫码浮层 '.player-smallhandle-big-image', '.player-gift-left .ab-icon.xsb-icon', // 其入口图标 '#pre-ab-video.new-pre-ab-video' ].join(','); function nuke(el) { if (!el) return; try { el.remove(); } catch (e) { el.parentNode && el.parentNode.removeChild(el); } } function killAdSlots() { var els = document.querySelectorAll(AD_SLOT_SEL); for (var i = 0; i < els.length; i++) { var el = els[i]; if (el.id === 'J_roomGgTop') { // 容器留壳(React 组件仍挂在上面)只清内容 if (el.innerHTML) { el.innerHTML = ''; DIAG.topAd++; mark('ad-slot-kill:J_roomGgTop'); } continue; } DIAG.sideAd++; if (String(el.className).indexOf('small') >= 0 || String(el.className).indexOf('xsb') >= 0) DIAG.shAd++; nuke(el); } // 右侧栏广告被清后会把 margin-bottom 设成 12px,顺手复位 var st = document.getElementById('J_roomSideTop'); if (st && st.style.marginBottom) st.style.marginBottom = ''; } function killAdVideo(v) { var box = null; try { v.pause(); box = v.closest('#pre-ab-video, #pre-ab-video-container, .new-pre-ab-video, [class*="ab-video"]'); v.removeAttribute('src'); v.srcObject = null; try { v.load(); } catch (e) {} } catch (e) {} nuke(box || v); mark('ad-video-killed'); } function adSweep() { if (!opt.skipAd) return; killAdSlots(); var sk = document.querySelector('.ab-skip'); if (sk) { try { sk.click(); } catch (e) {} } var vs = document.querySelectorAll('video'); for (var i = 0; i < vs.length; i++) { var v = vs[i]; if (v.id === 'hy-video') continue; var src = v.currentSrc || v.src || ''; if (v.classList.contains('ab-video') || AD_MEDIA_RE.test(src)) killAdVideo(v); } var boxes = document.querySelectorAll('#pre-ab-video.new-pre-ab-video'); for (var j = 0; j < boxes.length; j++) boxes[j].classList.remove('new-pre-ab-video'); var fs = document.querySelectorAll('iframe'); for (var k = 0; k < fs.length; k++) { if (AD_FRAME_RE.test(fs[k].src || '')) nuke(fs[k]); } } // 常驻广告位是页面按需注入的,只靠轮询会闪一下; // MutationObserver 在节点刚进 DOM 时就摘掉,用户看不到。 function startAdObserver() { try { var mo = new MutationObserver(function (muts) { for (var i = 0; i < muts.length; i++) { var added = muts[i].addedNodes; for (var j = 0; j < added.length; j++) { var n = added[j]; if (!n || n.nodeType !== 1) continue; if (n.matches && n.matches(AD_SLOT_SEL)) { if (n.id === 'J_roomGgTop') n.innerHTML = ''; else nuke(n); mark('ad-slot-kill:' + (n.id || n.className || n.tagName).toString().slice(0, 24)); DIAG.sideAd++; } if (n.querySelectorAll) { var inner = n.querySelectorAll(AD_SLOT_SEL); for (var k = 0; k < inner.length; k++) { if (inner[k].id === 'J_roomGgTop') inner[k].innerHTML = ''; else nuke(inner[k]); DIAG.sideAd++; } } } var t = muts[i].target; if (t && t.id === 'J_roomSideTop' && t.style && t.style.marginBottom) { t.style.marginBottom = ''; } } }); mo.observe(document.documentElement, { childList: true, subtree: true }); } catch (e) { mark('ad-obs-err'); } } function startAdGuard() { if (!opt.skipAd) return; adSweep(); startAdObserver(); setInterval(adSweep, 200); mark('ad-guard-ok'); } /* ------------------------------------------------------------------ * * 五、清晰度解锁 / 自动最高画质 * * 页面把档位信息存在 jQuery 的 data 里,点击处理器读同一个对象: * status "-1" → popLogin() ("请先登录"档) * 其它值 → H(li) 正常切换 * 所以把 status 改成 0 即可解锁。 * * 三点必须注意: * 1) 只能用页面自己的 jQuery(window.jQuery),沙箱里取不到 * 2) 列表会被重建,因此要持续改写,不能只做一次 * 3) HTMLElement.click() 产生的事件 isTrusted === false, * 可据此区分"脚本自动切"与"真人手动切",尊重用户选择 * ------------------------------------------------------------------ */ // done = 已切到目标档(列表结构一变就作废重来) // stop = 用户手动选了别的档,此后不再干预 // sig = 上一次看到的列表结构指纹 var AUTO = { done: false, stop: false, tries: 0, sig: '' }; function $page() { var jq = PAGE.jQuery || PAGE.$; return (jq && jq.fn) ? jq : null; } function currentOn(list) { var els = list.children; for (var i = 0; i < els.length; i++) { if (String(els[i].className).indexOf('on') >= 0) return els[i].textContent.trim(); } return null; } function applyUnlock(list) { var $ = $page(); if (!$) return 0; var els = list.children, n = 0; for (var i = 0; i < els.length; i++) { var $li = $(els[i]); var d = $li.data('data'); if (!d || typeof d !== 'object') continue; if (d.status === -1 || $li.children('.common-enjoy-btn').length) { d.status = 0; if (typeof d.iEnable === 'number') d.iEnable = 1; n++; } } if (n) DIAG.unlocked += n; // 视觉残留:点击逻辑只读 data,不看这个按钮 var btns = list.querySelectorAll('.bitrate-right-btn.common-enjoy-btn'); for (var b = 0; b < btns.length; b++) nuke(btns[b]); return n; } function bindQuality(list) { if (list.dataset.hyCapture) return; list.dataset.hyCapture = '1'; list.addEventListener('click', function (ev) { try { var $ = $page(); if (!$) return; var li = ev.target && ev.target.closest ? ev.target.closest('li') : null; if (!li) return; // 临门一脚:页面处理器执行前把 status 改写为 0 var d = $(li).data('data'); if (d && typeof d === 'object' && d.status === -1) { d.status = 0; if (typeof d.iEnable === 'number') d.iEnable = 1; mark('click-rescue'); } // 真人点击 → 尊重用户选择 if (ev.isTrusted === true) { var idx = -1, els = li.parentNode.children; for (var i = 0; i < els.length; i++) { if (els[i] === li) { idx = i; break; } } if (idx === 0) { AUTO.done = true; } else { AUTO.stop = true; mark('user-chose:' + li.textContent.trim()); } } } catch (e) {} }, true); } function tick() { var list = document.querySelector('#player-ctrl-wrap .player-videotype-list'); if (!list || list.children.length < 2) return; if (!$page()) return; bindQuality(list); applyUnlock(list); if (!opt.autoBestQuality || AUTO.stop) return; var first = list.children[0]; if (!first) return; // 列表是"先清空再逐项 append"建起来的,中途 first 可能是任意档位。 // 用结构指纹识别重建:指纹一变就重新评估,避免在残缺列表上误判成功。 var want = first.textContent.trim(); var sig = list.children.length + '|' + want; if (sig !== AUTO.sig) { AUTO.sig = sig; AUTO.done = false; } if (AUTO.done) return; // 必须真的点过至少一次,才算"切到目标档" if (AUTO.tries > 0 && currentOn(list) === want) { AUTO.done = true; DIAG.switched = true; mark('quality-on:' + want); return; } if (AUTO.tries >= 30) { AUTO.done = true; mark('quality-giveup'); return; } AUTO.tries++; DIAG.clicked++; try { first.click(); } catch (e) { mark('click-err'); } } function startQualityWatcher() { tick(); setInterval(tick, 400); mark('quality-watcher-ok'); } /* ------------------------------------------------------------------ * * 六、启动 * ------------------------------------------------------------------ */ function dumpDiag() { try { DIAG.live = !!document.getElementById('liveRoomObj'); DIAG.list = !!document.querySelector('#player-ctrl-wrap .player-videotype-list'); DIAG.on = (function () { var l = document.querySelector('#player-ctrl-wrap .player-videotype-list'); return l ? currentOn(l) : null; })(); DIAG.jq = $page() ? 'ok' : 'missing'; document.documentElement.setAttribute('data-hy-diag', JSON.stringify(DIAG)); } catch (e) {} } setInterval(dumpDiag, 1000); (function boot() { startAdGuard(); var t0 = Date.now(); (function loop() { if (document.getElementById('liveRoomObj') || document.getElementById('player-ctrl-wrap')) { mark('enter-room'); startQualityWatcher(); return; } if (Date.now() - t0 > 60000) { mark('no-room'); return; } setTimeout(loop, 250); })(); })(); })();