Auto PiP on Tab Switch

Auto Picture-in-Picture when switching tabs (only if video is playing)

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         Auto PiP on Tab Switch
// @name:ru      Авто PiP при переключении вкладок
// @namespace    http://tampermonkey.net/
// @version      1.2
// @description  Auto Picture-in-Picture when switching tabs (only if video is playing)
// @description:ru Автоматически включает режим "Картинка в картинке" (PiP), если вы ушли с вкладки и видео воспроизводится
// @author       FerNikoMF + ChatGPT Fix
// @match        *://*/*
// @grant        none
// @license      MIT
// @icon         https://i.imgur.com/0OXnhxm.png
// ==/UserScript==


(function() {
    'use strict';

    const ONLY_WHEN_PLAYING = true; // 💡
    let videoElement = null;
    let isPiP = false;

    function findVideo() {
        const videos = document.querySelectorAll('video');
        for (let video of videos) {
            if (video.readyState >= 2) {
                return video;
            }
        }
        return null;
    }

    document.addEventListener("visibilitychange", async () => {
        if (document.hidden) {
            videoElement = findVideo();
            if (videoElement && !document.pictureInPictureElement) {
                const canEnable = !ONLY_WHEN_PLAYING || !videoElement.paused;
                if (canEnable) {
                    try {
                        await videoElement.requestPictureInPicture();
                        isPiP = true;
                    } catch (error) {
                        console.warn("Не удалось включить PiP:", error.message);
                    }
                }
            }
        } else {
            if (document.pictureInPictureElement) {
                try {
                    await document.exitPictureInPicture();
                    isPiP = false;
                } catch (e) {
                    console.warn("Не удалось выключить PiP:", e.message);
                }
            }
        }
    });
})();