B站强制前台模式(禁止后台降级/软解)

让B站播放器始终认为页面在前台,避免因切到后台而触发省流、降清晰度、切软解等行为。 | 作者空间:https://space.bilibili.com/1319899187

คุณจะต้องติดตั้งส่วนขยาย เช่น Tampermonkey, Greasemonkey หรือ Violentmonkey เพื่อติดตั้งสคริปต์นี้

You will need to install an extension such as Tampermonkey to install this script.

คุณจะต้องติดตั้งส่วนขยาย เช่น Tampermonkey หรือ Violentmonkey เพื่อติดตั้งสคริปต์นี้

You will need to install an extension such as Tampermonkey or Userscripts to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==UserScript==
// @license MIT
// @name          B站强制前台模式(禁止后台降级/软解)
// @namespace     http://tampermonkey.net/
// @version       1.1
// @description   让B站播放器始终认为页面在前台,避免因切到后台而触发省流、降清晰度、切软解等行为。 | 作者空间:https://space.bilibili.com/1319899187
// @author        徐英珺、deepseek
// @match         *://*.bilibili.com/*
// @grant         none
// @run-at        document-start
// ==/UserScript==

(function() {
    'use strict';

    // ========== 1. 劫持 Page Visibility API ==========
    // 强制让 B 站认为页面永远可见(前台)
    Object.defineProperty(document, 'hidden', {
        get: function() { return false; },
        configurable: true,
        enumerable: true
    });
    Object.defineProperty(document, 'visibilityState', {
        get: function() { return 'visible'; },
        configurable: true,
        enumerable: true
    });

    // ========== 2. 阻止 visibilitychange 事件派发 ==========
    const origDispatchEvent = EventTarget.prototype.dispatchEvent;
    EventTarget.prototype.dispatchEvent = function(event) {
        if (event && event.type === 'visibilitychange') {
            // 直接忽略该事件,不向下传递
            return true;
        }
        return origDispatchEvent.call(this, event);
    };
})();