Resize YT To Window Size

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

当前为 2017-10-06 提交的版本,查看 最新版本

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