Resize YT To Window Size

Moves the YouTube video to the top of the website and fill the window with the video player.

目前為 2017-11-10 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name Resize YT To Window Size
  3. // @description Moves the YouTube video to the top of the website and fill the window with the video player.
  4. // @author Chris H (Zren / Shade)
  5. // @icon https://youtube.com/favicon.ico
  6. // @homepageURL https://github.com/Zren/ResizeYoutubePlayerToWindowSize/
  7. // @namespace http://xshade.ca
  8. // @version 111
  9. // @include http*://*.youtube.com/*
  10. // @include http*://youtube.com/*
  11. // @include http*://*.youtu.be/*
  12. // @include http*://youtu.be/*
  13. // @grant none
  14. // ==/UserScript==
  15.  
  16. // Github: https://github.com/Zren/ResizeYoutubePlayerToWindowSize
  17. // GreasyFork: https://greasyfork.org/scripts/811-resize-yt-to-window-size
  18. // OpenUserJS.org: https://openuserjs.org/scripts/zren/Resize_YT_To_Window_Size
  19. // Userscripts.org: http://userscripts-mirror.org/scripts/show/153699
  20.  
  21. (function (window) {
  22. "use strict";
  23.  
  24. //--- Settings
  25. var playerHeight = '100vh';
  26.  
  27. //--- Imported Globals
  28. // yt
  29. // ytcenter
  30. // html5Patched (Youtube+)
  31. // ytplayer
  32. var uw = window;
  33.  
  34. //--- Already Loaded?
  35. // GreaseMonkey loads this script twice for some reason.
  36. if (uw.ytwp) return;
  37.  
  38. //--- Is iframe?
  39. function inIframe () {
  40. try {
  41. return window.self !== window.top;
  42. } catch (e) {
  43. return true;
  44. }
  45. }
  46. if (inIframe()) return;
  47.  
  48. //--- Utils
  49. function isStringType(obj) { return typeof obj === 'string'; }
  50. function isArrayType(obj) { return obj instanceof Array; }
  51. function isObjectType(obj) { return typeof obj === 'object'; }
  52. function isUndefined(obj) { return typeof obj === 'undefined'; }
  53. function buildVenderPropertyDict(propertyNames, value) {
  54. var d = {};
  55. for (var i in propertyNames)
  56. d[propertyNames[i]] = value;
  57. return d;
  58. }
  59. function addClass(el, value) {
  60. var classes = value.split(' ');
  61. for (var i = 0; i < classes.length; i++) {
  62. el.classList.add(classes[i]);
  63. }
  64. }
  65. function removeClass(el, value) {
  66. var classes = value.split(' ');
  67. for (var i = 0; i < classes.length; i++) {
  68. el.classList.remove(classes[i]);
  69. }
  70. }
  71. function observe(selector, config, callback) {
  72. var observer = new MutationObserver(function(mutations) {
  73. mutations.forEach(function(mutation){
  74. callback(mutation);
  75. });
  76. });
  77. var target = document.querySelector(selector);
  78. if (!target) {
  79. return null;
  80. }
  81. observer.observe(target, config);
  82. return observer;
  83. }
  84.  
  85. //--- Stylesheet
  86. var JSStyleSheet = function(id) {
  87. this.id = id;
  88. this.stylesheet = '';
  89. };
  90.  
  91. JSStyleSheet.prototype.buildRule = function(selector, styles) {
  92. var s = "";
  93. for (var key in styles) {
  94. s += "\t" + key + ": " + styles[key] + ";\n";
  95. }
  96. return selector + " {\n" + s + "}\n";
  97. };
  98.  
  99. JSStyleSheet.prototype.appendRule = function(selector, k, v) {
  100. if (isArrayType(selector))
  101. selector = selector.join(',\n');
  102. var newStyle;
  103. if (!isUndefined(k) && !isUndefined(v) && isStringType(k)) { // v can be any type (as we stringify it).
  104. var d = {};
  105. d[k] = v;
  106. newStyle = this.buildRule(selector, d);
  107. } else if (!isUndefined(k) && isUndefined(v) && isObjectType(k)) {
  108. newStyle = this.buildRule(selector, k);
  109. } else {
  110. // Invalid Arguments
  111. console.log('Illegal arguments', arguments);
  112. return;
  113. }
  114.  
  115. this.stylesheet += newStyle;
  116. };
  117.  
  118. JSStyleSheet.injectIntoHeader = function(injectedStyleId, stylesheet) {
  119. var styleElement = document.getElementById(injectedStyleId);
  120. if (!styleElement) {
  121. styleElement = document.createElement('style');
  122. styleElement.type = 'text/css';
  123. styleElement.id = injectedStyleId;
  124. document.getElementsByTagName('head')[0].appendChild(styleElement);
  125. }
  126. styleElement.appendChild(document.createTextNode(stylesheet));
  127. };
  128.  
  129. JSStyleSheet.prototype.injectIntoHeader = function(injectedStyleId, stylesheet) {
  130. JSStyleSheet.injectIntoHeader(this.id, this.stylesheet);
  131. };
  132.  
  133. //--- History
  134. var HistoryEvent = function() {}
  135. HistoryEvent.listeners = []
  136.  
  137. HistoryEvent.dispatch = function(state, title, url) {
  138. var stack = this.listeners
  139. for (var i = 0, l = stack.length; i < l; i++) {
  140. stack[i].call(this, state, title, url)
  141. }
  142. }
  143. HistoryEvent.onPushState = function(state, title, url) {
  144. HistoryEvent.dispatch(state, title, url)
  145. return HistoryEvent.origPushState.apply(window.history, arguments)
  146. }
  147. HistoryEvent.onReplaceState = function(state, title, url) {
  148. HistoryEvent.dispatch(state, title, url)
  149. return HistoryEvent.origReplaceState.apply(window.history, arguments)
  150. }
  151. HistoryEvent.inject = function() {
  152. if (!HistoryEvent.injected) {
  153. HistoryEvent.origPushState = window.history.pushState
  154. HistoryEvent.origReplaceState = window.history.replaceState
  155.  
  156. window.history.pushState = HistoryEvent.onPushState
  157. window.history.replaceState = HistoryEvent.onReplaceState
  158. HistoryEvent.injected = true
  159. }
  160. }
  161.  
  162. HistoryEvent.timerId = 0
  163. HistoryEvent.onTick = function() {
  164. var currentPage = window.location.pathname + window.location.search
  165. if (HistoryEvent.lastPage != currentPage) {
  166. HistoryEvent.dispatch({}, document.title, window.location.href)
  167. HistoryEvent.lastPage = currentPage
  168. }
  169. }
  170. HistoryEvent.startTimer = function() {
  171. HistoryEvent.lastPage = window.location.pathname + window.location.search
  172. HistoryEvent.timerId = setInterval(HistoryEvent.onTick, 500)
  173. }
  174. HistoryEvent.stopTimer = function() {
  175. clearInterval(HistoryEvent.timerId)
  176. }
  177. window.ytwpHistoryEvent = HistoryEvent
  178.  
  179.  
  180. //--- Constants
  181. var scriptShortName = 'ytwp'; // YT Window Player
  182. var scriptStyleId = scriptShortName + '-style'; // ytwp-style
  183. var scriptBodyClassId = scriptShortName + '-window-player'; // .ytwp-window-player
  184. var viewingVideoClassId = scriptShortName + '-viewing-video'; // .ytwp-viewing-video
  185. var topOfPageClassId = scriptShortName + '-scrolltop'; // .ytwp-scrolltop
  186. var scriptBodyClassSelector = 'body.' + scriptBodyClassId; // body.ytwp-window-player
  187.  
  188. var videoContainerId = 'player';
  189. var videoContainerPlacemarkerId = scriptShortName + '-placemarker'; // ytwp-placemarker
  190.  
  191. var transitionProperties = ["transition", "-ms-transition", "-moz-transition", "-webkit-transition", "-o-transition"];
  192. var transformProperties = ["transform", "-ms-transform", "-moz-transform", "-webkit-transform", "-o-transform"];
  193.  
  194. //--- YTWP
  195. var ytwp = uw.ytwp = {
  196. scriptShortName: scriptShortName, // YT Window Player
  197. log_: function(logger, args) { logger.apply(console, ['[' + this.scriptShortName + '] '].concat(Array.prototype.slice.call(args))); return 1; },
  198. log: function() { return this.log_(console.log, arguments); },
  199. error: function() { return this.log_(console.error, arguments); },
  200.  
  201. initialized: false,
  202. pageReady: false,
  203. isWatchPage: false,
  204. };
  205.  
  206. ytwp.isWatchUrl = function (url) {
  207. if (!url)
  208. url = uw.location.href;
  209. return url.match(/https?:\/\/(www\.)?youtube.com\/watch\?/)
  210. || url.match(/https?:\/\/(www\.)?youtube.com\/(c|channel)\/[^\/]+\/live/);
  211. };
  212.  
  213. /*
  214. ytwp.playerWidth = window.innerWidth;
  215. ytwp.playerHeight = window.innerHeight;
  216. ytwp.moviePlayer = null;
  217. ytwp.updatePlayerSize = function() {
  218. //ytwp.moviePlayer = document.getElementById('movie_player');
  219. ytwp.moviePlayer = document.querySelector('.html5-video-player')
  220. if (ytwp.moviePlayer) {
  221. ytwp.playerWidth = ytwp.moviePlayer.clientWidth;
  222. ytwp.playerHeight = ytwp.moviePlayer.clientHeight;
  223. }
  224. console.log('updatePlayerSize', ytwp.playerWidth, ytwp.playerHeight)
  225. }
  226. ytwp.updatePlayerSize();
  227. window.addEventListener('resize', ytwp.updatePlayer, true);
  228.  
  229. ytwp.html5 = {
  230. app: null,
  231. YTRect: null,
  232. YTApplication: null,
  233. playerInstances: null,
  234. moviePlayerElement: null,
  235. };
  236. ytwp.html5.getPlayerRect = function() {
  237. return new ytwp.html5.YTRect(ytwp.playerWidth, ytwp.playerHeight);
  238. };
  239. ytwp.html5.getPlayerInstance = function() {
  240. if (!ytwp.html5.app) {
  241. // This will dispose and recreate the player
  242. // This is the only way to get the app instance since the list of players is no longer publicly exported in any way.
  243. // We could attempt to rewrite the <script>var ytplayer = ytplayer || {}; ... </script> before it executes, but that'd
  244. // be exceedingly difficult.
  245. var appInstance = yt.player.Application.create("player-api", ytplayer.config)
  246. ytwp.log('appInstance', appInstance)
  247. ytwp.html5.app = appInstance;
  248. }
  249. return ytwp.html5.app;
  250. };
  251. ytwp.html5.autohideControls = function() {
  252. var moviePlayerElement = document.getElementById('movie_player');
  253. if (!moviePlayerElement) return;
  254. // ytwp.log(moviePlayerElement.classList);
  255. removeClass(moviePlayerElement, 'autohide-controlbar autominimize-controls-aspect autohide-controls-fullscreenonly autohide-controls hide-controls-when-cued autominimize-progress-bar autominimize-progress-bar-fullscreenonly autohide-controlbar-fullscreenonly autohide-controls-aspect autohide-controls-fullscreen autominimize-progress-bar-non-aspect');
  256. addClass(moviePlayerElement, 'autominimize-progress-bar autohide-controls hide-controls-when-cued');
  257. // ytwp.log(moviePlayerElement.classList);
  258. };
  259. ytwp.html5.update = function() {
  260. if (!ytwp.html5.app)
  261. return;
  262. //ytwp.html5.updatePlayerInstance(ytwp.html5.app);
  263. ytwp.enterTheaterMode();
  264. };
  265. ytwp.html5.replaceClientRect = function(app, moviePlayerKey, clientRectFnKey) {
  266. var moviePlayer = app[moviePlayerKey];
  267. ytwp.html5.moviePlayerElement = moviePlayer.element;
  268. ytwp.html5.YTRect = moviePlayer[clientRectFnKey].call(moviePlayer).constructor;
  269. moviePlayer[clientRectFnKey] = ytwp.html5.getPlayerRect;
  270. };
  271. ytwp.html5.setRectFn = function(app, moviePlayerKey, clientRectFnKey) {
  272. ytwp.html5.moviePlayerElement = document.getElementById('movie_player');
  273. var moviePlayer = app[moviePlayerKey];
  274. ytwp.html5.YTRect = moviePlayer[clientRectFnKey].call(moviePlayer).constructor;
  275. moviePlayer.constructor.prototype[clientRectFnKey] = ytwp.html5.getPlayerRect;
  276. };
  277. ytwp.html5.updatePlayerInstance = function(app) {
  278. return;
  279.  
  280. if (!app) {
  281. return;
  282. }
  283.  
  284. var moviePlayerElement = document.getElementById('movie_player');
  285. var moviePlayer = null;
  286. var moviePlayerKey = null;
  287.  
  288. // function (){if(this.o){var a=this.Xa();if(!a.isEmpty()){var b=!g.Wd(a,g.Rg(this.B)),c=cZ(this);b&&(this.B.width=a.width,this.B.height=a.height);a=this.app.Z;(c||b||a.ka)&&this.app.g.Y("resize",this.Xa())}}}
  289. // Tail: this.app.g.Y("resize",this.Xa())}}}
  290. var applyFnRegex2 = /^function(\s*)\(\)\{.+this\.app\.([a-zA-Z_$][\w_$]*)\.([a-zA-Z_$][\w_$]*)\("resize",this\.([a-zA-Z_$][\w_$]*)\(\)\)\}\}\}$/;
  291. var applyKey2 = null;
  292.  
  293. // function (a){var b=this.j.X(),c=n$.L.xb.call(this);a||"detailpage"!=b.ma||b.ib||b.experiments.T||(c.height+=30);return c}
  294. // function (a){var b=this.app.X(),c=n$.M.xb.call(this);a||!JK(b)||b.ab||b.experiments.U||(c.height+=30);return c}
  295. var clientRectFnRegex1 = /^(function(\s*)\(a\)\{var b=this\.([a-zA-Z_$][\w_$]*)\.([a-zA-Z_$][\w_$]*)\(\)).*(\|\|\(c\.height\+=30\);return c})$/;
  296. // function (){var a=this.A.U();if(window.matchMedia){if((a.wb||a.Fb)&&window.matchMedia("(width: "+window.innerWidth+"px) and (height: "+window.innerHeight+"px)").matches)return new H(window.innerWidth,window.innerHeight);if("detailpage"==a.ja&&"blazer"!=a.j&&!a.Fb){a=a.experiments.A;if(window.matchMedia(S6.C).matches)return new H(426,a?280:240);var b=this.A.ha;if(window.matchMedia(b?S6.o:S6.j).matches)return new H(1280,a?760:720);if(b||window.matchMedia(S6.A).matches)return new H(854,a?520:480);if(window.matchMedia(S6.B).matches)return new H(640,a?400:360)}}return new H(this.element.clientWidth,this.element.clientHeight)}
  297. // Tail: return new H(this.element.clientWidth,this.element.clientHeight)}
  298. // function (){var a=this.app.T,b=Yh()==this.element;if(b&&Lp())return new g.ef(window.outerWidth,window.outerHeight);if(b||a.Xe){var c;window.matchMedia&&(a="(width: "+window.innerWidth+"px) and (height: "+window.innerHeight+"px)",this.F&&this.F.media==a||(this.F=window.matchMedia(a)),c=this.F&&this.F.matches);if(c)return new g.ef(window.innerWidth,window.innerHeight)}else if(this.N){if(a.experiments.ba("flex_theater_mode")&&this.app.fa||a.experiments.ba("player_scaling_360p_to_720p")&&this.da.matches)return new g.ef(this.element.clientWidth,this.element.clientHeight);if(this.N.matches)return new g.ef(426,240);a=this.app.fa;if((a?this.aa:this.$).matches)return new g.ef(1280,720);if(a||this.ca.matches)return new g.ef(854,480);if(this.fa.matches)return new g.ef(640,360)}return new g.ef(this.element.clientWidth,this.element.clientHeight)}
  299. // Tail: return new g.ef(this.element.clientWidth,this.element.clientHeight)}
  300. var clientRectFnRegex2 = /^(function(\s*)\()(.|\n)*(return new ([a-zA-Z_$][\w_$]*\.)?([a-zA-Z_$][\w_$]*)\(this\.element\.clientWidth,this\.element\.clientHeight\)})$/;
  301. var clientRectFn = null;
  302. var clientRectFnKey = null;
  303.  
  304. var fnAlreadyReplacedCount = 0;
  305.  
  306. for (var key1 in app) {
  307. var val1 = app[key1];//console.log(key1, val1);
  308. if (typeof val1 === 'object' && val1 !== null && val1.element === moviePlayerElement) {
  309. moviePlayer = val1;
  310. moviePlayerKey = key1;
  311.  
  312. for (var key2 in moviePlayer) {
  313. var val2 = moviePlayer[key2];//console.log(key1, key2, val2);
  314. if (typeof val2 === 'function') {
  315. var fnString = val2.toString();
  316. // console.log(fnString);
  317. if (clientRectFn === null && (clientRectFnRegex1.test(fnString) || clientRectFnRegex2.test(fnString))) {
  318. clientRectFn = val2;
  319. clientRectFnKey = key2;
  320. } else if (val2 === ytwp.html5.getPlayerRect) {
  321. fnAlreadyReplacedCount += 1;
  322. clientRectFn = val2;
  323. clientRectFnKey = key2;
  324. } else if (applyFnRegex2.test(fnString)) {
  325. console.log('applyFnRegex2', key1, key2, moviePlayerKey, applyKey2)
  326. applyKey2 = key2;
  327. } else {
  328. // console.log(key1, key2, val2, '[Not Used]');
  329. }
  330. }
  331. }
  332. }
  333. }
  334.  
  335. if (fnAlreadyReplacedCount > 0) {
  336. // return;
  337. }
  338.  
  339. if (moviePlayer === null || clientRectFn === null) {
  340. console.log('[ytwp] ', '[Error]', 'HTML5 Player has changed or there\'s multiple playerInstances and this one has been destroyed.');
  341. console.log('moviePlayer', moviePlayerKey, moviePlayer);
  342. console.log('clientRectFn', clientRectFnKey, clientRectFn);
  343. console.log('fnAlreadyReplacedCount', fnAlreadyReplacedCount);
  344. if (moviePlayer === null) {
  345. console.log('Debugging: moviePlayer');
  346. var table = [];
  347. Object.keys(app).forEach(function(key1) {
  348. var val1 = app[key1];
  349. table.push({
  350. key: key1,
  351. element: typeof val1 === 'object' && val1 !== null && val1.element === moviePlayerElement,
  352. val: val1,
  353. });
  354. });
  355. console.table(table);
  356. }
  357. if (moviePlayer != null) {
  358. console.log('Debugging: clientRectFn');
  359. var table = [];
  360. for (var key2 in moviePlayer) {
  361. var val2 = moviePlayer[key2];
  362. table.push({
  363. key: key2,
  364. returns: moviePlayer[key2] && moviePlayer[key2].toString().indexOf('return'),
  365. src: moviePlayer[key2] && moviePlayer[key2].toString(),
  366. });
  367. }
  368. console.table(table);
  369. }
  370. return;
  371. }
  372.  
  373. ytwp.html5.setRectFn(app, moviePlayerKey, clientRectFnKey);
  374. ytwp.log('ytwp.html5.setRectFn', moviePlayerKey, clientRectFnKey, app);
  375.  
  376. ytwp.log('applyKey check', !!(moviePlayer && applyKey2), moviePlayerKey, moviePlayer, applyKey2, moviePlayer[applyKey2]);
  377. if (moviePlayer && applyKey2) {
  378. ytwp.log('applyKey2', moviePlayerKey, applyKey2, moviePlayer[applyKey2]);
  379. // moviePlayer[applyKey2]('resize', ytwp.html5.getPlayerRect());
  380. try {
  381. moviePlayer[applyKey2]();
  382. } catch (e) {
  383. ytwp.error('error calling applyKey2')
  384. }
  385. } else {
  386. ytwp.log('applyFn not found');
  387. ytwp.moviePlayerKey = moviePlayerKey
  388. ytwp.moviePlayer = moviePlayer
  389. console.log('Debugging: applyFn');
  390. var table = [];
  391. for (var key2 in moviePlayer) {
  392. var val2 = moviePlayer[key2];
  393. table.push({
  394. key: key2,
  395. returns: moviePlayer[key2] && moviePlayer[key2].toString().indexOf('return'),
  396. src: moviePlayer[key2] && moviePlayer[key2].toString(),
  397. });
  398. }
  399. console.table(table);
  400. }
  401. };
  402. */
  403.  
  404.  
  405. ytwp.enterTheaterMode = function() {
  406. ytwp.log('enterTheaterMode')
  407. var watchElement = document.querySelector('ytd-watch:not([hidden])')
  408. if (watchElement) {
  409. if (!watchElement.hasAttribute('theater')) {
  410. var sizeButton = watchElement.querySelector('button.ytp-size-button')
  411. sizeButton.click()
  412. }
  413. watchElement.canFitTheater_ = true // When it's too small, it disables the theater mode.
  414. } else if (watchElement = document.querySelector('#page.watch')) {
  415. if (!watchElement.classList.contains('watch-stage-mode')) {
  416. var sizeButton = watchElement.querySelector('button.ytp-size-button')
  417. sizeButton.click()
  418. }
  419. }
  420. }
  421. ytwp.enterTheaterMode();
  422. uw.addEventListener('resize', ytwp.enterTheaterMode);
  423.  
  424. ytwp.init = function() {
  425. ytwp.log('init');
  426. if (!ytwp.initialized) {
  427. ytwp.isWatchPage = ytwp.isWatchUrl();
  428. if (ytwp.isWatchPage) {
  429. ytwp.removeSearchAutofocus();
  430. if (!document.getElementById(scriptStyleId)) {
  431. ytwp.event.initStyle();
  432. }
  433. ytwp.initScroller();
  434. ytwp.initialized = true;
  435. ytwp.pageReady = false;
  436. }
  437. }
  438. ytwp.event.onWatchInit();
  439. if (ytwp.isWatchPage) {
  440. ytwp.html5PlayerFix();
  441. }
  442. }
  443.  
  444. ytwp.initScroller = function() {
  445. // Register listener & Call it now.
  446. uw.addEventListener('scroll', ytwp.onScroll, false);
  447. uw.addEventListener('resize', ytwp.onScroll, false);
  448. ytwp.onScroll();
  449. }
  450.  
  451. ytwp.onScroll = function() {
  452. var viewportHeight = document.documentElement.clientHeight;
  453.  
  454. // topOfPageClassId
  455. if (ytwp.isWatchPage && uw.scrollY == 0) {
  456. document.body.classList.add(topOfPageClassId);
  457. //var player = document.getElementById('movie_player');
  458. //if (player)
  459. // player.focus();
  460. } else {
  461. document.body.classList.remove(topOfPageClassId);
  462. }
  463.  
  464. // viewingVideoClassId
  465. if (ytwp.isWatchPage && uw.scrollY <= viewportHeight) {
  466. document.body.classList.add(viewingVideoClassId);
  467. } else {
  468. document.body.classList.remove(viewingVideoClassId);
  469. }
  470. }
  471.  
  472. ytwp.event = {
  473. initStyle: function() {
  474. ytwp.log('initStyle');
  475. ytwp.style = new JSStyleSheet(scriptStyleId);
  476. ytwp.event.buildStylesheet();
  477. // Duplicate stylesheet targeting data-spf-name if enabled.
  478. if (uw.spf) {
  479. var temp = scriptBodyClassSelector;
  480. scriptBodyClassSelector = 'body[data-spf-name="watch"]';
  481. ytwp.event.buildStylesheet();
  482. ytwp.style.appendRule('body[data-spf-name="watch"]:not(.ytwp-window-player) #masthead-positioner', {
  483. 'position': 'absolute',
  484. 'top': playerHeight + ' !important'
  485. });
  486. }
  487. ytwp.style.injectIntoHeader();
  488. },
  489. buildStylesheet: function() {
  490. ytwp.log('buildStylesheet');
  491. //--- Browser Scrollbar
  492. ytwp.style.appendRule(scriptBodyClassSelector + '::-webkit-scrollbar', {
  493. 'width': '0',
  494. 'height': '0',
  495. });
  496.  
  497. //--- Video Player
  498. var d;
  499. d = buildVenderPropertyDict(transitionProperties, 'left 0s linear, padding-left 0s linear');
  500. d['padding'] = '0 !important';
  501. d['margin'] = '0 !important';
  502. ytwp.style.appendRule([
  503. scriptBodyClassSelector + ' #player',
  504. scriptBodyClassSelector + '.ytcenter-site-center.ytcenter-non-resize.ytcenter-guide-visible #player',
  505. scriptBodyClassSelector + '.ltr.ytcenter-site-center.ytcenter-non-resize.ytcenter-guide-visible.guide-collapsed #player',
  506. scriptBodyClassSelector + '.ltr.ytcenter-site-center.ytcenter-non-resize.ytcenter-guide-visible.guide-collapsed #player-legacy',
  507. scriptBodyClassSelector + '.ltr.ytcenter-site-center.ytcenter-non-resize.ytcenter-guide-visible.guide-collapsed #watch7-main-container',
  508. ], d);
  509. //
  510. d = buildVenderPropertyDict(transitionProperties, 'width 0s linear, left 0s linear');
  511.  
  512. // Bugfix for Firefox
  513. // Parts of the header (search box) are hidden under the player.
  514. // Firefox doesn't seem to be using the fixed header+guide yet.
  515. d['float'] = 'initial';
  516.  
  517. // Skinny mode
  518. d['left'] = 0;
  519. d['margin-left'] = 0;
  520.  
  521. ytwp.style.appendRule(scriptBodyClassSelector + ' #player-api', d);
  522.  
  523. // Theatre mode
  524. ytwp.style.appendRule(scriptBodyClassSelector + ' .watch-stage-mode #player .player-api', {
  525. 'left': 'initial',
  526. 'margin-left': 'initial',
  527. });
  528.  
  529. // Hide the cinema/wide mode button since it's useless.
  530. //ytwp.style.appendRule(scriptBodyClassSelector + ' #movie_player .ytp-size-button', 'display', 'none');
  531.  
  532. // !important is mainly for simplicity, but is needed to override the !important styling when the Guide is open due to:
  533. // .sidebar-collapsed #watch7-video, .sidebar-collapsed #watch7-main, .sidebar-collapsed .watch7-playlist { width: 945px!important; }
  534. // Also, Youtube Center resizes #player at element level.
  535. // Don't resize if Youtube+'s html.floater is detected.
  536. // Dont' resize if Youtube+ (Iridium/Material)'s html.iri-always-visible is detected.
  537. ytwp.style.appendRule(
  538. [
  539. scriptBodyClassSelector + ' #player',
  540. scriptBodyClassSelector + ' #player-api',
  541. 'html:not(.floater):not(.iri-always-visible) ' + scriptBodyClassSelector + ' #movie_player',
  542. scriptBodyClassSelector + ' #player-mole-container',
  543. 'html:not(.floater):not(.iri-always-visible) ' + scriptBodyClassSelector + ' .html5-video-container',
  544. 'html:not(.floater):not(.iri-always-visible) ' + scriptBodyClassSelector + ' .html5-main-video',
  545. ],
  546. {
  547. 'width': '100% !important',
  548. 'min-width': '100% !important',
  549. 'max-width': '100% !important',
  550. 'height': playerHeight + ' !important',
  551. 'min-height': playerHeight + ' !important',
  552. 'max-height': playerHeight + ' !important',
  553. }
  554. );
  555.  
  556. ytwp.style.appendRule(
  557. [
  558. scriptBodyClassSelector + ' #player',
  559. scriptBodyClassSelector + ' .html5-main-video',
  560. ],
  561. {
  562. 'top': '0 !important',
  563. 'right': '0 !important',
  564. 'bottom': '0 !important',
  565. 'left': '0 !important',
  566. }
  567. );
  568. // Resize #player-unavailable, #player-api
  569. // Using min/max width/height will keep
  570. ytwp.style.appendRule(scriptBodyClassSelector + ' #player .player-width', 'width', '100% !important');
  571. ytwp.style.appendRule(scriptBodyClassSelector + ' #player .player-height', 'height', '100% !important');
  572.  
  573. // Fix video overlays
  574. ytwp.style.appendRule([
  575. scriptBodyClassSelector + ' .html5-video-player .ad-container-single-media-element-annotations', // Ad
  576. scriptBodyClassSelector + ' .html5-video-player .ytp-upnext', // Autoplay Next Video
  577. ], 'top', '0');
  578.  
  579.  
  580. //--- Move Video Player
  581. ytwp.style.appendRule(scriptBodyClassSelector + ' #player', {
  582. 'position': 'absolute',
  583. // Already top:0; left: 0;
  584. });
  585. ytwp.style.appendRule(scriptBodyClassSelector, { // body
  586. 'margin-top': playerHeight,
  587. });
  588.  
  589. // Fix the top right avatar button
  590. ytwp.style.appendRule(scriptBodyClassSelector + ' button.ytp-button.ytp-cards-button', 'top', '0');
  591.  
  592.  
  593. //--- Sidebar
  594. // Remove the transition delay as you can see it moving on page load.
  595. d = buildVenderPropertyDict(transitionProperties, 'margin-top 0s linear, padding-top 0s linear');
  596. d['margin-top'] = '0 !important';
  597. d['top'] = '0 !important';
  598. ytwp.style.appendRule(scriptBodyClassSelector + ' #watch7-sidebar', d);
  599.  
  600. ytwp.style.appendRule(scriptBodyClassSelector + '.cardified-page #watch7-sidebar-contents', 'padding-top', '0');
  601.  
  602. //--- Absolutely position the fixed header.
  603. // Masthead
  604. d = buildVenderPropertyDict(transitionProperties, 'top 0s linear !important');
  605. ytwp.style.appendRule(scriptBodyClassSelector + '.hide-header-transition #masthead-positioner', d);
  606. ytwp.style.appendRule(scriptBodyClassSelector + '.' + viewingVideoClassId + ' #masthead-positioner', {
  607. 'position': 'absolute',
  608. 'top': playerHeight + ' !important'
  609. });
  610. // Lower masthead below Youtube+'s html.floater
  611. ytwp.style.appendRule('html.floater ' + scriptBodyClassSelector + '.' + viewingVideoClassId + ' #masthead-positioner', {
  612. 'z-index': '5',
  613. });
  614.  
  615. // Guide
  616. // When watching the video, we need to line it up with the masthead.
  617. ytwp.style.appendRule(scriptBodyClassSelector + '.' + viewingVideoClassId + ' #appbar-guide-menu', {
  618. 'display': 'initial',
  619. 'position': 'absolute',
  620. 'top': '100% !important' // Masthead height
  621. });
  622. ytwp.style.appendRule(scriptBodyClassSelector + '.' + viewingVideoClassId + ' #page.watch #guide', {
  623. 'display': 'initial',
  624. 'margin': '0',
  625. 'position': 'initial'
  626. });
  627.  
  628.  
  629. //---
  630. // Hide Scrollbars
  631. ytwp.style.appendRule(scriptBodyClassSelector + '.' + topOfPageClassId, 'overflow-x', 'hidden');
  632.  
  633.  
  634. //--- Fix Other Possible Style Issues
  635. ytwp.style.appendRule(scriptBodyClassSelector + ' #placeholder-player', 'display', 'none');
  636. ytwp.style.appendRule(scriptBodyClassSelector + ' #watch-sidebar-spacer', 'display', 'none');
  637. ytwp.style.appendRule(scriptBodyClassSelector + ' .skip-nav', 'display', 'none');
  638.  
  639. //--- Whitespace Leftover From Moving The Video
  640. ytwp.style.appendRule(scriptBodyClassSelector + ' #page.watch', 'padding-top', '0');
  641. ytwp.style.appendRule(scriptBodyClassSelector + ' .player-branded-banner', 'height', '0');
  642.  
  643. //--- Youtube+ Compatiblity
  644. ytwp.style.appendRule(scriptBodyClassSelector + ' #body-container', 'position', 'static');
  645. ytwp.style.appendRule('.part_static_size:not(.content-snap-width-skinny-mode) ' + scriptBodyClassSelector + ' .watch-non-stage-mode #player-playlist', 'width', '1066px');
  646.  
  647. //--- Playlist Bar
  648. ytwp.style.appendRule([
  649. scriptBodyClassSelector + ' #placeholder-playlist',
  650. scriptBodyClassSelector + ' #player .player-height#watch-appbar-playlist',
  651. ], {
  652. 'height': '540px !important',
  653. 'max-height': '540px !important',
  654. });
  655.  
  656. d = buildVenderPropertyDict(transitionProperties, 'transform 0s linear');
  657. ytwp.style.appendRule(scriptBodyClassSelector + ' #watch-appbar-playlist', d);
  658. d = buildVenderPropertyDict(transformProperties, 'translateY(0px)');
  659. d['margin-left'] = '0';
  660. d['top'] = 'calc(' + playerHeight + ' + 60px)';
  661. ytwp.style.appendRule(scriptBodyClassSelector + ' #player .player-height#watch-appbar-playlist', d);
  662. ytwp.style.appendRule(scriptBodyClassSelector + ' .playlist-videos-list', {
  663. 'max-height': '470px !important',
  664. 'height': 'initial !important',
  665. });
  666.  
  667. //---
  668. // Material UI
  669. ytwp.style.appendRule(scriptBodyClassSelector + '.ytwp-scrolltop #extra-buttons', 'display', 'none !important');
  670. // ytwp.style.appendRule('body > #player:not(.ytd-watch)', 'display', 'none');
  671. // ytwp.style.appendRule('body.ytwp-viewing-video #content:not(app-header-layout) ytd-page-manager', 'margin-top', '0 !important');
  672. // ytwp.style.appendRule('.ytd-watch-0 #content-separator.ytd-watch', 'margin-top', '0');
  673. ytwp.style.appendRule('ytd-app', 'position', 'static !important');
  674. ytwp.style.appendRule('ytd-watch #top', 'margin-top', '71px !important'); // 56px (topnav height) + 15px (margin)
  675. ytwp.style.appendRule('ytd-watch #container', 'margin-top', '0 !important');
  676. ytwp.style.appendRule('ytd-watch #content-separator', 'margin-top', '0 !important');
  677. ytwp.style.appendRule(scriptBodyClassSelector + '.ytwp-viewing-video ytd-app #masthead-container.ytd-app', {
  678. 'position': 'absolute',
  679. 'top': playerHeight,
  680. });
  681. ytwp.style.appendRule(scriptBodyClassSelector + '.ytwp-viewing-video ytd-watch #masthead-positioner', {
  682. 'top': playerHeight + ' !important',
  683. });
  684. },
  685. onWatchInit: function() {
  686. ytwp.log('onWatchInit');
  687. if (!ytwp.initialized) return;
  688. if (ytwp.pageReady) return;
  689.  
  690. ytwp.event.addBodyClass();
  691. ytwp.pageReady = true;
  692. },
  693. onDispose: function() {
  694. ytwp.log('onDispose');
  695. ytwp.initialized = false;
  696. ytwp.pageReady = false;
  697. ytwp.isWatchPage = false;
  698. /*
  699. ytwp.html5.app = null;
  700. // ytwp.html5.YTRect = null;
  701. ytwp.html5.YTApplication = null;
  702. ytwp.html5.playerInstances = null;
  703. //ytwp.html5.moviePlayerElement = null;
  704. */
  705. },
  706. addBodyClass: function() {
  707. // Insert CSS Into the body so people can style around the effects of this script.
  708. document.body.classList.add(scriptBodyClassId);
  709. ytwp.log('Applied ' + scriptBodyClassSelector);
  710. },
  711. };
  712.  
  713. ytwp.html5PlayerFix = function() {
  714. ytwp.log('html5PlayerFix');
  715. return;
  716.  
  717. try {
  718. if (!uw.ytcenter // Youtube Center
  719. && !uw.html5Patched // Youtube+
  720. && (!ytwp.html5.app)
  721. && (uw.ytplayer && uw.ytplayer.config)
  722. && (uw.yt && uw.yt.player && uw.yt.player.Application && uw.yt.player.Application.create)
  723. ) {
  724. ytwp.html5.app = ytwp.html5.getPlayerInstance();
  725. }
  726.  
  727. ytwp.html5.update();
  728. ytwp.html5.autohideControls();
  729. } catch (e) {
  730. ytwp.error(e);
  731. }
  732. }
  733.  
  734. ytwp.fixMasthead = function() {
  735. ytwp.log('fixMasthead');
  736. var el = document.querySelector('#masthead-positioner-height-offset');
  737. if (el) {
  738. ytwp.fixMastheadElement(el);
  739. }
  740. }
  741. ytwp.fixMastheadElement = function(el) {
  742. ytwp.log('fixMastheadElement', el);
  743. if (el.style.height) { // != ""
  744. setTimeout(function(){
  745. el.style.height = ""
  746. document.querySelector('#appbar-guide-menu').style.marginTop = "";
  747. }, 0);
  748. }
  749. }
  750.  
  751. JSStyleSheet.injectIntoHeader(scriptStyleId + '-focusfix', 'input#search[autofocus] { display: none; }');
  752. ytwp.removeSearchAutofocus = function() {
  753. var e = document.querySelector('input#search');
  754. ytwp.log('removeSearchAutofocus', e)
  755. if (e) {
  756. e.removeAttribute('autofocus')
  757. }
  758. }
  759.  
  760. ytwp.registerMastheadFix = function() {
  761. ytwp.log('registerMastheadFix');
  762. // Fix the offset when closing the Share widget (element.style.height = ~275px).
  763.  
  764. observe('#masthead-positioner-height-offset', {
  765. attributes: true,
  766. }, function(mutation) {
  767. console.log(mutation.type, mutation)
  768. if (mutation.attributeName === 'style') {
  769. var el = mutation.target;
  770. if (el.style.height) { // != ""
  771. setTimeout(function(){
  772. el.style.height = ""
  773. document.querySelector('#appbar-guide-menu').style.marginTop = "";
  774. }, 0);
  775. }
  776.  
  777. }
  778. });
  779. }
  780.  
  781. //--- Material UI
  782. ytwp.materialPageTransition = function() {
  783. ytwp.log('materialPageTransition')
  784. ytwp.init();
  785.  
  786. if (ytwp.isWatchUrl()) {
  787. ytwp.removeSearchAutofocus();
  788. ytwp.event.addBodyClass();
  789. // if (!ytwp.html5.app) {
  790. if (!ytwp.initialized) {
  791. ytwp.log('materialPageTransition !ytwp.html5.app', ytwp.html5.app)
  792. setTimeout(ytwp.materialPageTransition, 100);
  793. }
  794. var playerApi = document.querySelector('#player-api')
  795. if (playerApi) {
  796. playerApi.click()
  797. }
  798. } else {
  799. ytwp.event.onDispose();
  800. document.body.classList.remove(scriptBodyClassId);
  801. }
  802. ytwp.onScroll();
  803. ytwp.fixMasthead();
  804. ytwp.attemptToUpdatePlayer();
  805. };
  806.  
  807. //--- Listeners
  808. ytwp.registerListeners = function() {
  809. ytwp.registerMaterialListeners();
  810. ytwp.registerMastheadFix();
  811. };
  812.  
  813. ytwp.registerMaterialListeners = function() {
  814. // For Material UI
  815. HistoryEvent.listeners.push(ytwp.materialPageTransition);
  816. HistoryEvent.startTimer();
  817. // HistoryEvent.inject();
  818. // HistoryEvent.listeners.push(console.log.bind(console));
  819. };
  820.  
  821. ytwp.main = function() {
  822. ytwp.registerListeners();
  823. ytwp.init();
  824. ytwp.fixMasthead();
  825. };
  826.  
  827. ytwp.main();
  828.  
  829. ytwp.updatePlayerAttempts = -1;
  830. ytwp.updatePlayerMaxAttempts = 10;
  831. ytwp.attemptToUpdatePlayer = function() {
  832. console.log('ytwp.attemptToUpdatePlayer')
  833. if (0 <= ytwp.updatePlayerAttempts && ytwp.updatePlayerAttempts < ytwp.updatePlayerMaxAttempts) {
  834. ytwp.updatePlayerAttempts = 0;
  835. } else {
  836. ytwp.updatePlayerAttempts = 0;
  837. ytwp.attemptToUpdatePlayerTick();
  838. }
  839. }
  840. ytwp.attemptToUpdatePlayerTick = function() {
  841. console.log('ytwp.attemptToUpdatePlayerTick', ytwp.updatePlayerAttempts)
  842. if (ytwp.updatePlayerAttempts < ytwp.updatePlayerMaxAttempts) {
  843. ytwp.updatePlayerAttempts += 1;
  844. ytwp.updatePlayer();
  845. setTimeout(ytwp.attemptToUpdatePlayerTick, 200);
  846. }
  847. }
  848.  
  849. ytwp.updatePlayer = function() {
  850. ytwp.removeSearchAutofocus();
  851. ytwp.enterTheaterMode();
  852. /*
  853. ytwp.updatePlayerSize();
  854. if (ytwp.html5.app) {
  855. ytwp.html5.updatePlayerInstance(ytwp.html5.app);
  856. }
  857. ytwp.doMonkeyPatch();
  858. */
  859. }
  860.  
  861. ytwp.doMonkeyPatch = function() {
  862. ytwp.log('doMonkeyPatch')
  863.  
  864. // if (ytwp.patchKey) {
  865. // ytwp.log('doMonkeyPatch called with ytwp.patchKey already set', ytwp.patchKey)
  866. // return
  867. // }
  868.  
  869. if (!ytwp.isWatchUrl()) {
  870. ytwp.log('not watch page')
  871. return;
  872. }
  873.  
  874. // Chrome: function (a,b){return b?1==b?a.o:a.Ra[b]||null:a.C}
  875. // Firefox: function(a,b){return b?1==b?a.A:a.Sa[b]||null:a.D}
  876. var patchRegex = /^function(\s*)\(a,b\)\{return b\?1==b\?a\.([a-zA-Z_$][\w_$]*):a\.([a-zA-Z_$][\w_$]*)\[b\]\|\|null:a.([a-zA-Z_$][\w_$]*)\}$/;
  877. var patchKey = null;
  878.  
  879. if (window._yt_player) {
  880. ytwp.log('_yt_player exists')
  881. for (var key in window._yt_player) {
  882. var val = window._yt_player[key];
  883. if (typeof val === 'function') {
  884. var fnString = val.toString();
  885. // ytwp.log('', key, fnString)
  886. if (patchRegex.test(fnString)) {
  887. patchKey = key;
  888. break;
  889. }
  890. }
  891. }
  892. ytwp.log('patchKey', ytwp.patchKey, '=>', patchKey)
  893. if (patchKey) {
  894. try {
  895. ytwp.patchKey = patchKey
  896. if (!ytwp.patchOrigFn) {
  897. ytwp.patchOrigFn = window._yt_player[patchKey]
  898. ytwp.log('ytwp.patchOrigFn set', patchKey, ytwp.patchOrigFn)
  899. }
  900. window._yt_player[patchKey] = function(a,b) {
  901. ytwp.log('_yt_player.'+ytwp.patchKey, arguments);
  902. window._yt_player[ytwp.patchKey] = ytwp.patchOrigFn
  903. try {
  904. ytwp.html5.app = a
  905. ytwp.html5.updatePlayerInstance(a)
  906. } catch(e) {
  907. ytwp.error('error when trying to apply html5fix to app instance in _yt_player.'+ytwp.patchKey, arguments, e);
  908. }
  909. return ytwp.patchOrigFn.apply(this, arguments);
  910. }
  911. } catch(e) {
  912. ytwp.error('Could not monkey patch _yt_player.'+patchKey, e);
  913. ytwp.log('_yt_player', window._yt_player)
  914. ytwp.log('_yt_player.'+patchKey, window._yt_player ? window._yt_player[patchKey] : '')
  915. }
  916. }
  917. } else {
  918. ytwp.log('_yt_player not yet ready')
  919. setTimeout(ytwp.doMonkeyPatch, 100)
  920. }
  921. }
  922.  
  923. //ytwp.doMonkeyPatch()
  924. ytwp.materialPageTransition()
  925. setInterval(ytwp.updatePlayer, 1000);
  926.  
  927. })(typeof unsafeWindow !== 'undefined' ? unsafeWindow : window);