YouTube - Pause background videos

Pause videos playing in other background tabs. When you start playback of a video in foreground tab, background playback will be paused.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         YouTube - Pause background videos
// @namespace    q1k
// @version      1.0.1
// @description  Pause videos playing in other background tabs. When you start playback of a video in foreground tab, background playback will be paused.
// @author       q1k
// @match        *://www.youtube.com/*
// @grant        none
// @run-at       document-start
// ==/UserScript==

function findElement(selector) {
    return new Promise(function(resolve) {
        if (document.querySelector(selector)) {
            return resolve(document.querySelector(selector));
        }
        const observer = new MutationObserver(function(mutations) {
            if (document.querySelector(selector)) {
                resolve(document.querySelector(selector));
                observer.disconnect();
            }
        });
        observer.observe(document, {
            childList: true,
            subtree: true
        });
    });
}

var video;
const channel = new BroadcastChannel("video-channel");

findElement("#player #movie_player video").then(function(el){
    video = el;
    /*if(!!(video.currentTime > 0 && !video.paused && !video.ended && video.readyState > 2)) {
        channel.postMessage("pause");
    }*/
    Object.defineProperty(el, 'isplaying', {
        get: function(){
            return !!(this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);
        }
    });
    video.addEventListener("playing",function(){
        //start play, send pause
        if(document.hasFocus()){
            channel.postMessage("pause");
        }
    })
});

channel.addEventListener("message",function(ev){
    if(ev.data=="pause"){
        //received pause
        if(!document.hasFocus()){ //ignore if tab is active
            if(video.isplaying) {
                video.pause();
            }
        }
    }
});