youtube_speed: Add YouTube playback rate script

master
Taeyeon Mori 6 years ago
commit 1991d2075a
  1. 135
      youtube_speed.user.js

@ -0,0 +1,135 @@
// ==UserScript==
// @name YouTube Playback speed adjust
// @version 0.9
// @namespace userjs.osm
// @match *://www.youtube.com/*
// @grant none
// ==/UserScript==
"use strict";
class PlaySpeed {
// Dom accessors
get dom_video() {
return document.querySelector("video");
};
get dom_container() {
return document.getElementById("movie_player");
};
// Constructor
constructor() {
let self = this;
this.overlay = null;
this.rate = this.saved_rate;
this.domevent = window.addEventListener("DOMContentLoaded", () => {
let videos = document.getElementsByTagName("video");
if (videos[0])
videos[0].addEventListener("playing", () => {
// Refresh
self.set_rate(self.rate);
});
});
// Handle keypresses
this.keyevent = window.addEventListener("keydown", e => {
// [ :: Decrease speed
// ] :: Increase speed
// Shift- :: Smaller steps
// Alt- :: Coarser steps
if (e.keyCode === 219) // [
self.set_rate(self.rate - self.modifier_step(e));
else if (e.keyCode === 221) // ]
self.set_rate(self.rate + self.modifier_step(e));
// \ :: Restore speed
// Shift-\ :: Save speed
// Alt-\ :: Set speed to 1
else if (e.keyCode === 220) { // \
if (e.altKey)
self.set_rate(1);
else if (e.shiftKey)
self.save();
else
self.restore();
}
});
};
// Get step size from modifier keys
modifier_step(e) {
if (e.shiftKey == e.altKey)
return 0.1;
if (e.shiftKey)
return 0.01;
else if (e.altKey)
return 1;
};
// Speed overlay
do_overlay(rate) {
let div = this.dom_container;
let ol = this.overlay;
if (div) {
let need_overlay = Math.abs(rate - 1) > 0.001;
if (!need_overlay) {
if (ol) {
div.removeChild(ol);
ol = this.overlay = null;
}
return;
}
if (!ol) {
ol = this.overlay = document.createElement("div");
ol.style.position = "absolute";
ol.style.top = 0;
ol.style.left = 0;
ol.style.zIndex = 10;
div.appendChild(ol);
}
ol.textContent = rate.toPrecision(3);
}
};
// set rates
set_rate(rate) {
this.dom_video.playbackRate = rate;
this.do_overlay(rate);
this.rate = rate;
};
// Restore from localstorage
get lst_key() {
return "yt_playspeed_adjust";
};
get saved_rate() {
let saved = window.localStorage.getItem(this.lst_key);
if (saved)
return parseFloat(saved);
else
return 1;
}
restore() {
this.set_rate(this.saved_rate);
}
save() {
window.localStorage.setItem(this.lst_key, this.rate.toPrecision(5));
}
};
const yt_playspeed = new PlaySpeed();
Loading…
Cancel
Save