YouTube Wait for Me - Pause and Start Player in Background Tabs

Pause the video in YouTube tabs opened in the background, play on activation 2016-08-18 (I know, it doesn't pause fast enough)

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name        YouTube Wait for Me - Pause and Start Player in Background Tabs
// @author      Jefferson "jscher2000" Scher
// @namespace   JeffersonScher
// @version     0.7
// @copyright   Copyright 2016 Jefferson Scher
// @license     BSD 3-clause
// @description Pause the video in YouTube tabs opened in the background, play on activation 2016-08-18 (I know, it doesn't pause fast enough)
// @include     http*://www.youtube.com/*
// @grant       none
// ==/UserScript==
// See: https://developer.mozilla.org/docs/Web/API/Page_Visibility_API

var videoElement = document.querySelector('#movie_player video');
if (videoElement){
  if (document["hidden"]) { // background tab
    // Mute the player ASAP
    videoElement.muted = true;
    // Pause the player
    videoElement.pause();
    // Seek to the beginning
    videoElement.currentTime = 0;
    // Set up event handler to watch for tab becoming visible
    document.addEventListener("visibilitychange", handleVisibilityChange, false);
  }
}

function handleVisibilityChange() {
  if (document["hidden"]) {
    // Pause the player
    videoElement.pause();
  } else {
    // Resume the video after a quarter second
    window.setTimeout(function(){videoElement.play()}, 250);
    videoElement.muted = false;
    // We're not going to pause again, so remove event listener
    document.removeEventListener("visibilitychange", handleVisibilityChange, false);
  }
}