LatBel

Userscript for audio background (YouTube and YouTube music)

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

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

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         LatBel
// @namespace    http://tampermonkey.net/
// @version      1.6
// @description  Userscript for audio background (YouTube and YouTube music)
// @author       dehacking_guy
// @license      MIT
// @match        *://*/*
// @grant        none
// @run-at       document-start
// ==/UserScript==

(function() {
    'use strict';

    // 1. Block tab switching detection completely
    Object.defineProperty(document, 'hidden', {value: false, writable: false});
    Object.defineProperty(document, 'visibilityState', {value: 'visible', writable: false});

    const blockEvent = (event) => event.stopImmediatePropagation();
    ['visibilitychange', 'webkitvisibilitychange', 'pagehide', 'blur'].forEach(evt => {
        window.addEventListener(evt, blockEvent, true);
    });

    // 2. Aggressive Playback Enforcement
    document.addEventListener('pause', (event) => {
        const target = event.target;
        
        if (target && target.tagName === 'VIDEO') {
            if (!document.hasFocus()) {
                
                let attempts = 0;
                // Try to force play every 500ms
                const forcePlay = setInterval(() => {
                    attempts++;
                    target.play().then(() => {
                        // If successful, stop the loop
                        clearInterval(forcePlay); 
                    }).catch(err => {
                        console.warn('Screen-off auto-play blocked by OS:', err);
                    });

                    // Give up after 10 attempts (5 seconds) to prevent crashing the page
                    if (attempts >= 10) {
                        clearInterval(forcePlay);
                    }
                }, 500);
            }
        }
    }, true);
})();