Auto Picture-in-Picture when switching tabs (only if video is playing)
// ==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);
}
}
}
});
})();