// ==UserScript== // @name 防切屏暂停视频 - 伪装页面始终置顶 // @namespace 428720006@qq.com // @version 1.2 // @description 拦截页面可见性检测,伪装网页始终处于前台/可见状态,防止切屏后视频自动暂停 // @author qq428720006 // @match *://*/* // @grant none // @run-at document-start // 页面加载前就执行,避免检测逻辑先运行 // ==/UserScript== (function() { 'use strict'; // 核心:重写页面可见性相关属性,强制返回「可见」状态 const overrideVisibilityProps = () => { // 重写 document.visibilityState(始终返回 visible) Object.defineProperty(document, 'visibilityState', { get: () => 'visible', configurable: true }); // 重写 document.hidden(始终返回 false,表示未隐藏) Object.defineProperty(document, 'hidden', { get: () => false, configurable: true }); // 兼容webkit内核(如Safari/部分Chrome) Object.defineProperty(document, 'webkitVisibilityState', { get: () => 'visible', configurable: true }); Object.defineProperty(document, 'webkitHidden', { get: () => false, configurable: true }); }; // 拦截可见性变化事件,阻止其触发 const blockVisibilityEvents = () => { const eventNames = [ 'visibilitychange', 'webkitvisibilitychange', 'mozvisibilitychange', 'msvisibilitychange' ]; eventNames.forEach(eventName => { // 拦截事件监听 const originalAddListener = document.addEventListener; document.addEventListener = function(type, listener, options) { if (type === eventName) { return; // 跳过监听可见性变化事件 } return originalAddListener.call(this, type, listener, options); }; // 拦截事件触发 const originalDispatch = document.dispatchEvent; document.dispatchEvent = function(event) { if (event.type === eventName) { return true; // 阻止事件派发 } return originalDispatch.call(this, event); }; }); }; // 伪装页面始终处于激活状态(拦截blur事件、重写hasFocus) const fakePageActive = () => { // 重写 document.hasFocus() 始终返回true Object.defineProperty(document, 'hasFocus', { value: () => true, configurable: true }); // 拦截window的blur事件(部分网站通过blur检测切屏) const originalAddWinListener = window.addEventListener; window.addEventListener = function(type, listener, options) { if (type === 'blur' || type === 'focusout') { return; // 跳过监听失焦事件 } return originalAddWinListener.call(this, type, listener, options); }; // 强制页面保持focus状态 window.addEventListener('blur', () => { window.focus(); // 切屏后立即重新获取焦点(可选,部分场景有用) }, { once: false }); }; // 执行所有伪装逻辑 overrideVisibilityProps(); blockVisibilityEvents(); fakePageActive(); // 动态监测:防止部分网站后期重写属性,定时重置 setInterval(() => { overrideVisibilityProps(); fakePageActive(); }, 1000); // 每秒重置一次,应对动态修改的网站 })();