Pause videos playing in background tabs when a video starts
目前為
// ==UserScript==
// @name YouTube - Pause background videos
// @namespace anhkhoakz
// @version 1.1.0
// @description Pause videos playing in background tabs when a video starts
// playing in the foreground tab.
// @author anhkhoakz
// @license GPLv3; https://www.gnu.org/licenses/gpl-3.0.html#license-text
// @match *://www.youtube.com/*
// @grant none
// @run-at document-start
// ==/UserScript==
(() => {"use strict";var K=(j)=>{return new Promise((q)=>{let A=document.querySelector(j);if(A)return q(A);let B=new MutationObserver(()=>{let z=document.querySelector(j);if(!z)return;q(z),B.disconnect()});B.observe(document,{childList:!0,subtree:!0})})},M=(j)=>{return j.currentTime>0&&!j.paused&&!j.ended&&j.readyState>=3},C=()=>{return document.hasFocus()},O=(j,q)=>{return j==="pause"&&!C()&&q.isPlaying};(()=>{let j=null,q=new BroadcastChannel("video-channel");K("#player #movie_player video").then((x)=>{j=x,Object.defineProperty(j,"isPlaying",{get:function(){return M(this)}}),j.addEventListener("playing",()=>{if(C())q.postMessage("pause")},{passive:!0}),j.addEventListener("loadeddata",()=>{if(C())q.postMessage("pause")},{passive:!0}),j.addEventListener("canplay",()=>{if(C())q.postMessage("pause")},{passive:!0})}),document.addEventListener("visibilitychange",()=>{if(!document.hidden&&j?.isPlaying)q.postMessage("pause")},{passive:!0});let A="",B="",z=()=>{let x=document.querySelector("#player #movie_player video");if(x){let D=x.src,G=new URLSearchParams(new URL(D).search).get("v")||"";if(D!==A||G!==B){if(A=D,B=G,C())q.postMessage("pause")}}};setInterval(z,1000),window.addEventListener("popstate",z),window.addEventListener("pushstate",z),window.addEventListener("replacestate",z);let{pushState:H,replaceState:J}=history;history.pushState=(...x)=>{H.apply(history,x),setTimeout(z,100)},history.replaceState=(...x)=>{J.apply(history,x),setTimeout(z,100)},q.addEventListener("message",(x)=>{if(!j||!O(x.data,j))return;j.pause()},{passive:!0})})();})();