youtube HTML5 Auto Loop

youtubeHTML5プレイヤー再生時に自動ループする

目前为 2017-02-11 提交的版本。查看 最新版本

// ==UserScript===
// @name           youtube HTML5 Auto Loop
// @namespace      youtube HTML5 Auto Loop
// @grant          none
// @description    youtubeHTML5プレイヤー再生時に自動ループする
// @author         TNB
// @match          *://*.youtube.com/*
// @version        1.0
// ==/UserScript==

var loop_off = {
  when_enable_next_video_autoplay: false,
  when_playlist: false,
  with_embedded_video: false
};

var YoutubeHTML5AutoLoop = {
  loop: '',
  eventCache: {},
  isLoop: function() {
    var ele = {when_enable_next_video_autoplay:'input[type="checkbox"]:checked+label .unchecked', when_playlist:'#watch-appbar-playlist', with_embedded_video:'html[dir]'};
    for (var i in loop_off) {
      if (loop_off[i] && document.querySelector(ele[i])) {
        return false;
      }
    }
    return true;
  },
  init: function() {
    this.loop = this.isLoop();
    this.addListener();
  },
  loopOn: function() {
    var video = document.getElementsByTagName('video')[0];
    if (this.loop) {
      video.setAttribute('loop', '');
    } else {
      video.removeAttribute('loop');
    }
  },
  loopToggle: function() {
    this.loop = this.loop? false: true;
    this.loopOn();
  },
  loopDisplay: function() {
    var video = document.querySelector('video:hover');
    if (video) {
      var checkBox = document.querySelector('[aria-checked]');
      checkBox.setAttribute('aria-checked', this.loop);
      if (!this.eventCache.addLoopToggle) {
        checkBox.addEventListener('click', this, false);
        this.eventCache.addLoopToggle = true;
      }
    }
  },
  watchAjax: function() {
    var content = document.getElementById('page');
    if (content) {
      var ev = new CustomEvent('completedRequest'),
          mo = new MutationObserver(function(){window.dispatchEvent(ev)});
      mo.observe(content, {attributes:true, attributeFilter:['class']});
    }
  },
  addListener: function() {
    if (!this.eventCache.loadEvent) {
      window.addEventListener('load', this, false);
      window.addEventListener('contextmenu', this, false);
      window.addEventListener('completedRequest', this, false);
      this.eventCache.loadEvent = true;
    }
    if (loop_off.when_enable_next_video_autoplay) {
      var autoplay = document.getElementById('autoplay-checkbox');
      if (autoplay) {
        autoplay.addEventListener('click', this, false);
      }
    }
  },
  handleEvent: function(e) {
    switch(e.type) {
      case 'load':
        this.watchAjax();
        this.loopOn();
        break;
      case 'contextmenu':
        this.loopDisplay();
        break;
      case 'click':
        this.loopToggle();
        break;
      case 'completedRequest':
        this.init();
        this.loopOn();
        break;
    }
  }
};

YoutubeHTML5AutoLoop.init();