Attempts to Save Resources by Auto Pausing/Playing Different Open Twitch Streams
当前为
// ==UserScript==
// @name Twitch Auto Pause/Play Toggle for Tab Switch
// @namespace http://userstyles.org
// @description Attempts to Save Resources by Auto Pausing/Playing Different Open Twitch Streams
// @author 636597
// @include *://*.twitch.tv/*
// @run-at document-start
// @version 0.3
// ==/UserScript==
var PLAYING = true;
var PAUSE_PLAY_BUTTON_ELEMENT = false;
var CHECKING_FOCUS = true;
var button_element = false;
function toggleCheckFocus() {
if ( CHECKING_FOCUS ) {
console.log( "Stopping Observing the Focus" );
clearObserver();
button_element.innerHTML = 'Observe Focus';
}
else {
console.log( "Starting Observing the Focus" );
loadObserver();
button_element.innerHTML = 'Stop Observing Focus';
}
CHECKING_FOCUS = !CHECKING_FOCUS;
}
function addToggleCheckFocusButton() {
//var title_element = document.querySelector( 'h2[data-a-target="stream-title"]' );
var title_element = document.querySelector( 'div[data-test-selector="chat-input-buttons-container"' )
//if ( !title_element ) { return; }
var id = "toggle-check-focus";
var element_string = '<button id="' + id + '">Stop Observing Focus</button>';
var template = document.createElement( 'template' );
template.innerHTML = element_string;
var fragment = template.content
title_element.insertBefore( fragment , title_element.childNodes[ title_element.childNodes.length - 1 ] );
button_element = document.body.querySelector( "#" + id );
button_element.addEventListener( "click" , function( event ) {
toggleCheckFocus();
});
}
function checkFocus() {
if ( document.hasFocus() ) {
// console.log( "tab enter" );
// console.log( "PLAYING === " + PLAYING );
if ( !PLAYING ) {
console.log( "Tab Entered: Toggling Play State" );
PAUSE_PLAY_BUTTON_ELEMENT.click();
PLAYING = true;
}
} else {
// console.log( "tab leave" );
// console.log( "PLAYING === " + PLAYING );
if ( PLAYING ) {
console.log( "Tab Left: Toggling Play State" );
PAUSE_PLAY_BUTTON_ELEMENT.click();
PLAYING = false;
}
}
}
// Maybe It Be Converted to Observer Somehow
var observer_interval = false;
function clearObserver() {
clearInterval( observer_interval );
}
function loadObserver() {
console.log( PAUSE_PLAY_BUTTON_ELEMENT );
if ( !PAUSE_PLAY_BUTTON_ELEMENT ) { return; }
observer_interval = setInterval( checkFocus, 1000 );
}
// Init
(function() {
var ready = setInterval(function(){
var x1 = document.querySelectorAll( 'button.player-button' );
if ( x1 ) { if ( x1[ 0 ] ) {
PAUSE_PLAY_BUTTON_ELEMENT = x1[0];
clearInterval( ready );
addToggleCheckFocusButton();
loadObserver();
}}
} , 2 );
setTimeout( function() {
clearInterval( ready );
} , 10000 );
})();