Greasy Fork is available in English.

Resize YT To Window Size

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

  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. // @license MIT
  6. // @icon https://s.ytimg.com/yts/img/favicon_32-vflOogEID.png
  7. // @homepageURL https://github.com/Zren/ResizeYoutubePlayerToWindowSize/
  8. // @namespace http://xshade.ca
  9. // @version 139
  10. // @include http*://*.youtube.com/*
  11. // @include http*://youtube.com/*
  12. // @include http*://*.youtu.be/*
  13. // @include http*://youtu.be/*
  14. // @grant none
  15. // ==/UserScript==
  16.  
  17. // Github: https://github.com/Zren/ResizeYoutubePlayerToWindowSize
  18. // GreasyFork: https://greatest.deepsurf.us/scripts/811-resize-yt-to-window-size
  19. // OpenUserJS.org: https://openuserjs.org/scripts/zren/Resize_YT_To_Window_Size
  20. // Userscripts.org: http://userscripts-mirror.org/scripts/show/153699
  21.  
  22. (function (window) {
  23. "use strict";
  24.  
  25. //--- Settings
  26. var playerHeight = '100vh';
  27. var enableOnLoad = true;
  28. var scriptToggleKey = 'w';
  29.  
  30. //--- Imported Globals
  31. // yt
  32. // ytcenter
  33. // html5Patched (Youtube+)
  34. // ytplayer
  35. var uw = window;
  36.  
  37. //--- Already Loaded?
  38. // GreaseMonkey loads this script twice for some reason.
  39. if (uw.ytwp) return;
  40.  
  41. //--- Is iframe?
  42. function inIframe () {
  43. try {
  44. return window.self !== window.top;
  45. } catch (e) {
  46. return true;
  47. }
  48. }
  49. if (inIframe()) return;
  50.  
  51. //--- Utils
  52. function isStringType(obj) { return typeof obj === 'string'; }
  53. function isArrayType(obj) { return obj instanceof Array; }
  54. function isObjectType(obj) { return typeof obj === 'object'; }
  55. function isUndefined(obj) { return typeof obj === 'undefined'; }
  56. function buildVenderPropertyDict(propertyNames, value) {
  57. var d = {};
  58. for (var i in propertyNames)
  59. d[propertyNames[i]] = value;
  60. return d;
  61. }
  62. function observe(selector, config, callback) {
  63. var observer = new MutationObserver(function(mutations) {
  64. mutations.forEach(function(mutation){
  65. callback(mutation);
  66. });
  67. });
  68. var target = document.querySelector(selector);
  69. if (!target) {
  70. return null;
  71. }
  72. observer.observe(target, config);
  73. return observer;
  74. }
  75.  
  76. //--- Stylesheet
  77. var JSStyleSheet = function(id) {
  78. this.id = id;
  79. this.stylesheet = '';
  80. };
  81.  
  82. JSStyleSheet.prototype.buildRule = function(selector, styles) {
  83. var s = "";
  84. for (var key in styles) {
  85. s += "\t" + key + ": " + styles[key] + ";\n";
  86. }
  87. return selector + " {\n" + s + "}\n";
  88. };
  89.  
  90. JSStyleSheet.prototype.appendRule = function(selector, k, v) {
  91. if (isArrayType(selector))
  92. selector = selector.join(',\n');
  93. var newStyle;
  94. if (!isUndefined(k) && !isUndefined(v) && isStringType(k)) { // v can be any type (as we stringify it).
  95. var d = {};
  96. d[k] = v;
  97. newStyle = this.buildRule(selector, d);
  98. } else if (!isUndefined(k) && isUndefined(v) && isObjectType(k)) {
  99. newStyle = this.buildRule(selector, k);
  100. } else {
  101. // Invalid Arguments
  102. console.log('Illegal arguments', arguments);
  103. return;
  104. }
  105.  
  106. this.stylesheet += newStyle;
  107. };
  108.  
  109. JSStyleSheet.injectIntoHeader = function(injectedStyleId, stylesheet) {
  110. var styleElement = document.getElementById(injectedStyleId);
  111. if (!styleElement) {
  112. styleElement = document.createElement('style');
  113. styleElement.type = 'text/css';
  114. styleElement.id = injectedStyleId;
  115. document.getElementsByTagName('head')[0].appendChild(styleElement);
  116. }
  117. styleElement.appendChild(document.createTextNode(stylesheet));
  118. };
  119.  
  120. JSStyleSheet.prototype.injectIntoHeader = function() {
  121. JSStyleSheet.injectIntoHeader(this.id, this.stylesheet);
  122. };
  123.  
  124. //--- History
  125. var HistoryEvent = function() {}
  126. HistoryEvent.listeners = []
  127.  
  128. HistoryEvent.dispatch = function(state, title, url) {
  129. var stack = this.listeners
  130. for (var i = 0, l = stack.length; i < l; i++) {
  131. stack[i].call(this, state, title, url)
  132. }
  133. }
  134. HistoryEvent.onPushState = function(state, title, url) {
  135. HistoryEvent.dispatch(state, title, url)
  136. return HistoryEvent.origPushState.apply(window.history, arguments)
  137. }
  138. HistoryEvent.onReplaceState = function(state, title, url) {
  139. HistoryEvent.dispatch(state, title, url)
  140. return HistoryEvent.origReplaceState.apply(window.history, arguments)
  141. }
  142. HistoryEvent.inject = function() {
  143. if (!HistoryEvent.injected) {
  144. HistoryEvent.origPushState = window.history.pushState
  145. HistoryEvent.origReplaceState = window.history.replaceState
  146.  
  147. window.history.pushState = HistoryEvent.onPushState
  148. window.history.replaceState = HistoryEvent.onReplaceState
  149. HistoryEvent.injected = true
  150. }
  151. }
  152.  
  153. HistoryEvent.timerId = 0
  154. HistoryEvent.onTick = function() {
  155. var currentPage = window.location.pathname + window.location.search
  156. if (HistoryEvent.lastPage != currentPage) {
  157. HistoryEvent.dispatch({}, document.title, window.location.href)
  158. HistoryEvent.lastPage = currentPage
  159. }
  160. }
  161. HistoryEvent.startTimer = function() {
  162. HistoryEvent.lastPage = window.location.pathname + window.location.search
  163. HistoryEvent.timerId = setInterval(HistoryEvent.onTick, 500)
  164. }
  165. HistoryEvent.stopTimer = function() {
  166. clearInterval(HistoryEvent.timerId)
  167. }
  168. window.ytwpHistoryEvent = HistoryEvent
  169.  
  170.  
  171. //--- Constants
  172. var scriptShortName = 'ytwp'; // YT Window Player
  173. var scriptStyleId = scriptShortName + '-style'; // ytwp-style
  174. var scriptBodyClassId = scriptShortName + '-window-player'; // .ytwp-window-player
  175. var viewingVideoClassId = scriptShortName + '-viewing-video'; // .ytwp-viewing-video
  176. var topOfPageClassId = scriptShortName + '-scrolltop'; // .ytwp-scrolltop
  177.  
  178. var scriptHtmlSelector = 'html:not([fullscreen="true"])';
  179. var scriptBodySelector = 'body.' + scriptBodyClassId; // body.ytwp-window-player
  180. scriptBodySelector += ':not(.enhancer-for-youtube-pinned-player)'; // Support "Enhancer for Youtube" (Pull Request #51)
  181. var scriptSelector = scriptHtmlSelector + ' ' + scriptBodySelector;
  182.  
  183. var videoContainerId = 'player';
  184. var videoContainerPlacemarkerId = scriptShortName + '-placemarker'; // ytwp-placemarker
  185.  
  186. var transitionProperties = ["transition", "-ms-transition", "-moz-transition", "-webkit-transition", "-o-transition"];
  187. var transformProperties = ["transform", "-ms-transform", "-moz-transform", "-webkit-transform", "-o-transform"];
  188.  
  189. //--- YTWP
  190. var ytwp = uw.ytwp = {
  191. scriptShortName: scriptShortName, // YT Window Player
  192. log_: function(logger, args) { logger.apply(console, ['[' + this.scriptShortName + '] '].concat(Array.prototype.slice.call(args))); return 1; },
  193. log: function() { return this.log_(console.log, arguments); },
  194. error: function() { return this.log_(console.error, arguments); },
  195.  
  196. initialized: false,
  197. pageReady: false,
  198. isWatchPage: false,
  199. };
  200.  
  201. ytwp.debugPage = function() {
  202. function prettyHtml(el) {
  203. var s = el.outerHTML
  204. return s.substr(0, s.indexOf('>')+1)
  205. }
  206. var defStyle = {
  207. 'display':'block', 'position': 'static',
  208. 'left': 'auto', 'right': 'auto', 'top': 'auto', 'bottom': 'auto',
  209. 'padding-left':'0px', 'padding-right':'0px', 'padding-top':'0px', 'padding-bottom':'0px',
  210. 'margin-left':'0px', 'margin-right':'0px', 'margin-top':'0px', 'margin-bottom':'0px',
  211. 'width': 'auto', 'min-width': 'auto', 'max-width': 'auto',
  212. 'height': 'auto', 'min-height': 'auto', 'max-height': 'auto',
  213. }
  214. var keyFilter = Object.keys(defStyle)
  215. var node = document.querySelector('#movie_player video')
  216. var outStr = ''
  217. while (node && node.parentNode) {
  218. var style = getComputedStyle(node)
  219. var styleDiff = {}
  220. for (var key of style) {
  221. if (keyFilter.includes(key) && style[key] != defStyle[key]) {
  222. styleDiff[key] = style[key]
  223. }
  224. }
  225. outStr += prettyHtml(node) + ' ' + JSON.stringify(styleDiff) + '\n'
  226. node = node.parentNode
  227. }
  228. outStr = outStr.split('\n').reverse().join('\n')
  229. ytwp.log('debugPage', outStr)
  230. }
  231.  
  232. ytwp.hasYoutubeChanged = function() {
  233. var tree = [
  234. 'html',
  235. 'body',
  236. 'ytd-app',
  237. '#content.ytd-app',
  238. 'ytd-page-manager#page-manager.ytd-app',
  239. 'ytd-watch-flexy.ytd-page-manager',
  240. '#full-bleed-container.ytd-watch-flexy',
  241. '#player-full-bleed-container.ytd-watch-flexy',
  242. '#player-container.ytd-watch-flexy',
  243. 'ytd-player#ytd-player.ytd-watch-flexy',
  244. '#container.ytd-player',
  245. '.html5-video-player',
  246. '.html5-video-container',
  247. 'video.html5-main-video',
  248. ]
  249. tree = tree.reverse()
  250. var node = document.querySelector(tree[0])
  251. if (!node) {
  252. ytwp.error('YT has changed!', tree[0], 'no longer exists!')
  253. return true
  254. }
  255. for (var i = 1; i < tree.length; i++) {
  256. var parent = node.parentNode
  257. var selector = tree[i]
  258. if (parent.matches(selector)) {
  259. node = parent
  260. } else {
  261. ytwp.error('YT has changed!', selector, 'no longer exists!')
  262. }
  263. }
  264. return false
  265. }
  266.  
  267. ytwp.isWatchUrl = function (url) {
  268. if (!url)
  269. url = uw.location.href;
  270. if (url.match(/https?:\/\/(www\.)?youtube.com\/(c|channel|user)\/[^\/]+\/live/)) {
  271. if (document.querySelector('ytd-browse')) {
  272. return false
  273. } else {
  274. return true
  275. }
  276. }
  277. return url.match(/https?:\/\/(www\.)?youtube.com\/watch\?/);
  278. };
  279.  
  280. ytwp.setTheaterMode = function(enable) {
  281. // ytwp.log('setTheaterMode', enable)
  282.  
  283. var watchElement = document.querySelector('ytd-watch:not([hidden])') || document.querySelector('ytd-watch-flexy:not([hidden])') || document.querySelector('ytd-watch-grid:not([hidden])')
  284. if (watchElement) {
  285. var isTheater = watchElement.hasAttribute('theater')
  286. if (enable != isTheater) {
  287. // Note: (Issue #75) ytd-watch-flexy watchElement.querySelector() will find
  288. // Nothing for some reason. We need to query from the document scope.
  289. var sizeButton = document.querySelector(watchElement.tagName + ':not([hidden]) button.ytp-size-button')
  290. if (!sizeButton) {
  291. var screenModeButtons = document.querySelectorAll(watchElement.tagName + ':not([hidden]) button.ytp-screen-mode-settings-button')
  292. sizeButton = screenModeButtons[1] // 2nd button is "Theater mode (t)"
  293. }
  294. if (sizeButton) {
  295. sizeButton.click()
  296. }
  297. }
  298. watchElement.canFitTheater_ = true // When it's too small, it disables the theater mode.
  299. } else if (watchElement = document.querySelector('#page.watch')) {
  300. var isTheater = watchElement.classList.contains('watch-stage-mode')
  301. if (enable != isTheater) {
  302. var sizeButton = watchElement.querySelector('button.ytp-size-button')
  303. if (sizeButton) {
  304. sizeButton.click()
  305. }
  306. }
  307. }
  308. }
  309. ytwp.enterTheaterMode = function() {
  310. // ytwp.log('enterTheaterMode')
  311. if (!document.body.classList.contains(scriptBodyClassId)) {
  312. return
  313. }
  314.  
  315. ytwp.setTheaterMode(true)
  316. }
  317. ytwp.enterTheaterMode();
  318. uw.addEventListener('resize', ytwp.enterTheaterMode);
  319.  
  320. ytwp.detectPlayerUnavailable = function() {
  321. if (document.querySelector('[player-unavailable]')) {
  322. ytwp.event.removeBodyClass()
  323. }
  324. }
  325.  
  326.  
  327. ytwp.init = function() {
  328. ytwp.log('init');
  329. if (!ytwp.initialized) {
  330. ytwp.isWatchPage = ytwp.isWatchUrl();
  331. if (ytwp.isWatchPage) {
  332. ytwp.removeSearchAutofocus();
  333. if (!document.getElementById(scriptStyleId)) {
  334. ytwp.event.initStyle();
  335. }
  336. ytwp.initScroller();
  337. ytwp.initialized = true;
  338. ytwp.pageReady = false;
  339. }
  340. }
  341. ytwp.event.onWatchInit();
  342. if (ytwp.isWatchPage) {
  343. ytwp.html5PlayerFix();
  344. }
  345. }
  346.  
  347. ytwp.initScroller = function() {
  348. // Register listener & Call it now.
  349. uw.addEventListener('scroll', ytwp.onScroll, false);
  350. uw.addEventListener('resize', ytwp.onScroll, false);
  351. ytwp.onScroll();
  352. }
  353.  
  354. ytwp.onScroll = function() {
  355. var viewportHeight = document.documentElement.clientHeight;
  356.  
  357. // topOfPageClassId
  358. if (ytwp.isWatchPage && uw.scrollY == 0) {
  359. document.body.classList.add(topOfPageClassId);
  360. //var player = document.getElementById('movie_player');
  361. //if (player)
  362. // player.focus();
  363. } else {
  364. document.body.classList.remove(topOfPageClassId);
  365. }
  366.  
  367. // viewingVideoClassId
  368. if (ytwp.isWatchPage && uw.scrollY <= viewportHeight) {
  369. document.body.classList.add(viewingVideoClassId);
  370. } else {
  371. document.body.classList.remove(viewingVideoClassId);
  372. }
  373. }
  374.  
  375. ytwp.event = {
  376. initStyle: function() {
  377. ytwp.log('initStyle');
  378. ytwp.style = new JSStyleSheet(scriptStyleId);
  379. ytwp.event.buildStylesheet();
  380. // Duplicate stylesheet targeting data-spf-name if enabled.
  381. if (uw.spf) {
  382. var temp = scriptBodySelector;
  383. scriptBodySelector = 'body[data-spf-name="watch"]';
  384. scriptSelector = scriptHtmlSelector + ' ' + scriptBodySelector
  385. ytwp.event.buildStylesheet();
  386. ytwp.style.appendRule('body[data-spf-name="watch"]:not(.ytwp-window-player) #masthead-positioner', {
  387. 'position': 'absolute',
  388. 'top': playerHeight + ' !important'
  389. });
  390. }
  391. ytwp.style.injectIntoHeader();
  392. },
  393. buildStylesheet: function() {
  394. ytwp.log('buildStylesheet');
  395. //--- Browser Scrollbar
  396. // Chrome/Webkit
  397. ytwp.style.appendRule(scriptBodySelector + '::-webkit-scrollbar', {
  398. 'width': '0 !important',
  399. 'height': '0 !important',
  400. });
  401. // Firefox/Gecko
  402. // Requires about:config flag to be toggled as of FireFox v63
  403. // https://github.com/Zren/ResizeYoutubePlayerToWindowSize/issues/42
  404. ytwp.style.appendRule('html', {
  405. 'scrollbar-width': 'none',
  406. });
  407.  
  408. //--- Video Player
  409. var d;
  410. d = buildVenderPropertyDict(transitionProperties, 'left 0s linear, padding-left 0s linear');
  411. d['padding'] = '0 !important';
  412. d['margin'] = '0 !important';
  413. ytwp.style.appendRule([
  414. scriptBodySelector + ' #player',
  415. scriptBodySelector + '.ytcenter-site-center.ytcenter-non-resize.ytcenter-guide-visible #player',
  416. scriptBodySelector + '.ltr.ytcenter-site-center.ytcenter-non-resize.ytcenter-guide-visible.guide-collapsed #player',
  417. scriptBodySelector + '.ltr.ytcenter-site-center.ytcenter-non-resize.ytcenter-guide-visible.guide-collapsed #player-legacy',
  418. scriptBodySelector + '.ltr.ytcenter-site-center.ytcenter-non-resize.ytcenter-guide-visible.guide-collapsed #watch7-main-container',
  419. ], d);
  420. //
  421. d = buildVenderPropertyDict(transitionProperties, 'width 0s linear, left 0s linear');
  422.  
  423. // Bugfix for Firefox
  424. // Parts of the header (search box) are hidden under the player.
  425. // Firefox doesn't seem to be using the fixed header+guide yet.
  426. d['float'] = 'initial';
  427.  
  428. // Skinny mode
  429. d['left'] = 0;
  430. d['margin-left'] = 0;
  431.  
  432. ytwp.style.appendRule(scriptBodySelector + ' #player-api', d);
  433.  
  434. // Theater mode
  435. ytwp.style.appendRule(scriptBodySelector + ' .watch-stage-mode #player .player-api', {
  436. 'left': 'initial !important',
  437. 'margin-left': 'initial !important',
  438. });
  439.  
  440. // Hide the cinema/wide mode button since it's useless.
  441. //ytwp.style.appendRule(scriptBodySelector + ' #movie_player .ytp-size-button', 'display', 'none');
  442.  
  443. // !important is mainly for simplicity, but is needed to override the !important styling when the Guide is open due to:
  444. // .sidebar-collapsed #watch7-video, .sidebar-collapsed #watch7-main, .sidebar-collapsed .watch7-playlist { width: 945px!important; }
  445. // Also, Youtube Center resizes #player at element level.
  446. // Don't resize if Youtube+'s html.floater is detected.
  447. // Dont' resize if Youtube+ (Iridium/Material)'s html.iri-always-visible is detected.
  448. ytwp.style.appendRule(
  449. [
  450. scriptSelector + ' #player',
  451. scriptSelector + ' #player-wrap',
  452. scriptSelector + ' #player-api',
  453. scriptHtmlSelector + ':not(.floater):not(.iri-always-visible) ' + scriptBodySelector + ' #movie_player',
  454. scriptSelector + ' #player-mole-container',
  455. scriptHtmlSelector + ':not(.floater):not(.iri-always-visible) ' + scriptBodySelector + ' .html5-video-container',
  456. scriptHtmlSelector + ':not(.floater):not(.iri-always-visible) ' + scriptBodySelector + ' .html5-main-video',
  457. scriptSelector + ' ytd-watch-flexy[theater] #player-theater-container.ytd-watch-flexy',
  458. scriptSelector + ' ytd-watch-flexy[flexy] #player-container-outer.ytd-watch-flexy',
  459. scriptSelector + ' ytd-watch-flexy[flexy] #player-container-inner.ytd-watch-flexy',
  460. scriptSelector + ' ytd-watch-flexy[flexy] #player-container.ytd-watch-flexy',
  461. scriptSelector + ' ytd-watch-grid[theater] #player-theater-container.ytd-watch-grid',
  462. scriptSelector + ' ytd-watch-grid[flexy] #player-container-outer.ytd-watch-grid',
  463. scriptSelector + ' ytd-watch-grid[flexy] #player-container-inner.ytd-watch-grid',
  464. scriptSelector + ' ytd-watch-grid[flexy] #player-container.ytd-watch-grid',
  465. ],
  466. {
  467. 'width': '100% !important',
  468. 'min-width': '100% !important',
  469. 'max-width': '100% !important',
  470. 'height': playerHeight + ' !important',
  471. 'min-height': playerHeight + ' !important',
  472. 'max-height': playerHeight + ' !important',
  473. }
  474. );
  475.  
  476. ytwp.style.appendRule(
  477. [
  478. scriptSelector + ' #player',
  479. scriptSelector + ' .html5-main-video',
  480. ],
  481. {
  482. 'top': '0 !important',
  483. 'right': '0 !important',
  484. 'bottom': '0 !important',
  485. 'left': '0 !important',
  486. }
  487. );
  488. // Resize #player-unavailable, #player-api
  489. // Using min/max width/height will keep
  490. ytwp.style.appendRule(scriptSelector + ' #player .player-width', 'width', '100% !important');
  491. ytwp.style.appendRule(scriptSelector + ' #player .player-height', 'height', '100% !important');
  492.  
  493. // Fix video overlays
  494. ytwp.style.appendRule([
  495. scriptSelector + ' .html5-video-player .ad-container-single-media-element-annotations', // Ad
  496. scriptSelector + ' .html5-video-player .ytp-upnext', // Autoplay Next Video
  497. ], 'top', '0');
  498.  
  499. // Fix video cropping (object-fit: cover) (Issue #70)
  500. ytwp.style.appendRule(scriptSelector + ' .ytp-fit-cover-video .html5-main-video', 'object-fit', 'contain !important');
  501. // Thumbnail cropping
  502. ytwp.style.appendRule(scriptSelector + ' .ytp-cued-thumbnail-overlay-image', {
  503. 'background-size': 'contain !important',
  504. '-moz-background-size': 'contain !important',
  505. '-webkit-background-size': 'contain !important',
  506. });
  507.  
  508. //--- Video Container Background
  509. ytwp.style.appendRule(scriptSelector + ' #movie_player', 'background-color', '#000000');
  510.  
  511. //--- Move Video Player
  512. ytwp.style.appendRule(scriptSelector + ' #player', {
  513. 'position': 'absolute',
  514. // Already top:0; left: 0;
  515. });
  516. ytwp.style.appendRule(scriptSelector, { // body
  517. 'margin-top': playerHeight,
  518. });
  519.  
  520. // Fix the top right avatar button
  521. ytwp.style.appendRule(scriptSelector + ' button.ytp-button.ytp-cards-button', 'top', '0');
  522.  
  523.  
  524. //--- Sidebar
  525. // Remove the transition delay as you can see it moving on page load.
  526. d = buildVenderPropertyDict(transitionProperties, 'margin-top 0s linear, padding-top 0s linear');
  527. d['margin-top'] = '0 !important';
  528. d['top'] = '0 !important';
  529. ytwp.style.appendRule(scriptSelector + ' #watch7-sidebar', d);
  530.  
  531. ytwp.style.appendRule(scriptSelector + '.cardified-page #watch7-sidebar-contents', 'padding-top', '0');
  532.  
  533. //--- Absolutely position the fixed header.
  534. // Masthead
  535. ytwp.style.appendRule('#skip-navigation.ytd-masthead', 'top', '-150vh'); // Normally -1000px can be shorter than screen (Issue #77)
  536. d = buildVenderPropertyDict(transitionProperties, 'top 0s linear !important');
  537. ytwp.style.appendRule(scriptSelector + '.hide-header-transition #masthead-positioner', d);
  538. ytwp.style.appendRule(scriptSelector + '.' + viewingVideoClassId + ' #masthead-positioner', {
  539. 'position': 'absolute',
  540. 'top': playerHeight + ' !important'
  541. });
  542. // Lower masthead below Youtube+'s html.floater
  543. ytwp.style.appendRule('html.floater ' + scriptBodySelector + '.' + viewingVideoClassId + ' #masthead-positioner', {
  544. 'z-index': '5',
  545. });
  546. // Autocomplete popup
  547. ytwp.style.appendRule(scriptSelector + ' .sbdd_a', {
  548. 'top': '56px',
  549. });
  550. ytwp.style.appendRule(scriptSelector + '.' + viewingVideoClassId + ' .sbdd_a', {
  551. 'top': 'calc(' + playerHeight + ' + 56px) !important',
  552. 'position': 'absolute !important',
  553. });
  554.  
  555. // Guide
  556. // When watching the video, we need to line it up with the masthead.
  557. ytwp.style.appendRule(scriptSelector + '.' + viewingVideoClassId + ' #appbar-guide-menu', {
  558. 'display': 'initial',
  559. 'position': 'absolute',
  560. 'top': '100% !important' // Masthead height
  561. });
  562. ytwp.style.appendRule(scriptSelector + '.' + viewingVideoClassId + ' #page.watch #guide', {
  563. 'display': 'initial',
  564. 'margin': '0',
  565. 'position': 'initial'
  566. });
  567. // When the guide is open, it adds body{top:-1000px} which messes with the top position (Issue #77)
  568. ytwp.style.appendRule(scriptSelector + '.lock-scrollbar', {
  569. 'top': '0 !important',
  570. 'position': 'static !important',
  571. });
  572.  
  573.  
  574. //---
  575. // MiniPlayer-Bar
  576. ytwp.style.appendRule(scriptSelector + ' #miniplayer-bar #player', {
  577. 'position': 'static',
  578. });
  579. ytwp.style.appendRule(
  580. [
  581. scriptSelector + ' #miniplayer-bar #player',
  582. scriptSelector + ' #miniplayer-bar #player-api',
  583. scriptHtmlSelector + ':not(.floater):not(.iri-always-visible) ' + scriptBodySelector + ' #miniplayer-bar #movie_player',
  584. scriptSelector + ' #player-mole-container',
  585. scriptHtmlSelector + ':not(.floater):not(.iri-always-visible) ' + scriptBodySelector + ' #miniplayer-bar .html5-video-container',
  586. scriptHtmlSelector + ':not(.floater):not(.iri-always-visible) ' + scriptBodySelector + ' #miniplayer-bar .html5-main-video',
  587. ],
  588. {
  589. 'width': '252px !important',
  590. 'min-width': '252px !important',
  591. 'max-width': '252px !important',
  592. 'height': '142px !important',
  593. 'min-height': '142px !important',
  594. 'max-height': '142px !important',
  595. }
  596. );
  597. // Override inline style (caused by a JS animation) that breaks the miniplayer video
  598. // https://github.com/Zren/ResizeYoutubePlayerToWindowSize/issues/41#issuecomment-439710130
  599. ytwp.style.appendRule('.video-stream.html5-main-video', {
  600. 'top': '0 !important',
  601. });
  602.  
  603. //---
  604. // Hide Scrollbars
  605. ytwp.style.appendRule(scriptSelector + '.' + topOfPageClassId, 'overflow-x', 'hidden');
  606.  
  607.  
  608. //--- Fix Other Possible Style Issues
  609. ytwp.style.appendRule(scriptSelector + ' #placeholder-player', 'display', 'none');
  610. ytwp.style.appendRule(scriptSelector + ' #watch-sidebar-spacer', 'display', 'none');
  611. ytwp.style.appendRule(scriptSelector + ' .skip-nav', 'display', 'none');
  612.  
  613. //--- Whitespace Leftover From Moving The Video
  614. ytwp.style.appendRule(scriptSelector + ' #page.watch', 'padding-top', '0');
  615. ytwp.style.appendRule(scriptSelector + ' .player-branded-banner', 'height', '0');
  616.  
  617. //--- Youtube+ Compatiblity
  618. ytwp.style.appendRule(scriptSelector + ' #body-container', 'position', 'static');
  619. ytwp.style.appendRule(scriptHtmlSelector + '.part_static_size:not(.content-snap-width-skinny-mode) ' + scriptBodySelector + ' .watch-non-stage-mode #player-playlist', 'width', '1066px');
  620.  
  621. //--- Playlist Bar
  622. ytwp.style.appendRule([
  623. scriptSelector + ' #placeholder-playlist',
  624. scriptSelector + ' #player .player-height#watch-appbar-playlist',
  625. ], {
  626. 'height': '540px !important',
  627. 'max-height': '540px !important',
  628. });
  629.  
  630. d = buildVenderPropertyDict(transitionProperties, 'transform 0s linear');
  631. ytwp.style.appendRule(scriptSelector + ' #watch-appbar-playlist', d);
  632. d = buildVenderPropertyDict(transformProperties, 'translateY(0px)');
  633. d['margin-left'] = '0';
  634. d['top'] = 'calc(' + playerHeight + ' + 60px)';
  635. ytwp.style.appendRule(scriptSelector + ' #player .player-height#watch-appbar-playlist', d);
  636. ytwp.style.appendRule(scriptSelector + ' .playlist-videos-list', {
  637. 'max-height': '470px !important',
  638. 'height': 'initial !important',
  639. });
  640.  
  641. // Old layout `&disable_polymer=true`
  642. ytwp.style.appendRule(scriptSelector + ' #player .player-height#watch-appbar-playlist', {
  643. 'left': 'calc((100vw - 1066px)/2 + 640px + 10px)',
  644. 'width': '416px',
  645. });
  646. ytwp.style.stylesheet += '@media screen and (min-height: 630px) and (min-width: 1294px) {\n';
  647. ytwp.style.appendRule(scriptSelector + ' #player .player-height#watch-appbar-playlist', {
  648. 'left': 'calc((100vw - 1280px)/2 + 854px + 10px)',
  649. });
  650. ytwp.style.stylesheet += '}\n @media screen and (min-width: 1720px) and (min-height:980px) {\n';
  651. ytwp.style.appendRule(scriptSelector + ' #player .player-height#watch-appbar-playlist', {
  652. 'left': 'calc((100vw - 1706px)/2 + 1280px + 10px)',
  653. });
  654. ytwp.style.stylesheet += '}\n';
  655.  
  656. //---
  657. // Material UI
  658. ytwp.style.appendRule(scriptSelector + '.ytwp-scrolltop #extra-buttons', 'display', 'none !important');
  659. // ytwp.style.appendRule('body > #player:not(.ytd-watch)', 'display', 'none');
  660. // ytwp.style.appendRule('body.ytwp-viewing-video #content:not(app-header-layout) ytd-page-manager', 'margin-top', '0 !important');
  661. // ytwp.style.appendRule('.ytd-watch-0 #content-separator.ytd-watch', 'margin-top', '0');
  662. ytwp.style.appendRule('ytd-app', 'position', 'static !important');
  663. ytwp.style.appendRule('ytd-watch #top', 'margin-top', '71px !important'); // 56px (topnav height) + 15px (margin)
  664. ytwp.style.appendRule('ytd-watch #container', 'margin-top', '0 !important');
  665. ytwp.style.appendRule('ytd-watch #content-separator', 'margin-top', '0 !important');
  666. // Note: Container is now relative since 2023 June (Issue #77)
  667. // Note: Container is now a full-bleed-player (Issue #79)
  668. ytwp.style.appendRule([
  669. scriptSelector + ' ytd-watch-flexy[theater] #player-wide-container.ytd-watch-flexy',
  670. scriptSelector + ' ytd-watch-flexy[fullscreen] #player-wide-container.ytd-watch-flexy',
  671. scriptSelector + ' ytd-watch-flexy[full-bleed-player] #player-full-bleed-container.ytd-watch-flexy', // Issue #79 (2023-08-17)
  672. scriptSelector + ' ytd-watch-flexy[full-bleed-player] #full-bleed-container.ytd-watch-flexy', // Issue #79 (2023-08-22)
  673. scriptSelector + ' ytd-watch-grid[theater] #player-wide-container.ytd-watch-grid',
  674. scriptSelector + ' ytd-watch-grid[fullscreen] #player-wide-container.ytd-watch-grid',
  675. scriptSelector + ' ytd-watch-grid[full-bleed-player] #player-full-bleed-container.ytd-watch-grid', // Issue #81 (2023-08-30)
  676. scriptSelector + ' ytd-watch-grid[full-bleed-player] #full-bleed-container.ytd-watch-grid', // Issue #81 (2023-08-30)
  677. ], {
  678. 'position': 'static',
  679. 'height': 0,
  680. 'min-height': 0,
  681. });
  682.  
  683. ytwp.style.appendRule(scriptSelector + '.ytwp-viewing-video ytd-app #masthead-container.ytd-app', {
  684. 'position': 'absolute',
  685. 'top': playerHeight,
  686. 'z-index': 0,
  687. });
  688. ytwp.style.appendRule(scriptSelector + '.ytwp-viewing-video ytd-watch #masthead-positioner', {
  689. 'top': playerHeight + ' !important',
  690. });
  691. ytwp.style.appendRule(scriptSelector + ' .ytp-cued-thumbnail-overlay', 'z-index', '10');
  692.  
  693. //---
  694. // Flexy UI
  695. ytwp.style.appendRule([
  696. scriptSelector + ' ytd-watch-flexy[theater] #player-theater-container.ytd-watch-flexy',
  697. scriptSelector + ' ytd-watch-grid[theater] #player-theater-container.ytd-watch-grid',
  698. ], {
  699. 'position': 'absolute',
  700. 'top': '0',
  701. });
  702. // Youtube seems to be ignoring the margin/padding top in certain elements for some reason (Issue #88)
  703. // ytwp.style.appendRule([
  704. // scriptSelector + ' ytd-watch-flexy',
  705. // scriptSelector + ' ytd-watch-grid',
  706. // ], 'padding-top', '71px'); // 56px (topnav height) + 15px (margin)
  707. ytwp.style.appendRule('#page-manager.ytd-app', 'padding-top', 'var(--ytd-masthead-height,var(--ytd-toolbar-height))');
  708. ytwp.style.appendRule(scriptSelector + ' #error-screen', 'z-index', '11');
  709. },
  710. onWatchInit: function() {
  711. ytwp.log('onWatchInit');
  712. if (!ytwp.initialized) return;
  713. if (ytwp.pageReady) return;
  714.  
  715. if (enableOnLoad) {
  716. ytwp.event.addBodyClass();
  717. }
  718. if (ytwp.hasYoutubeChanged()) {
  719. ytwp.debugPage()
  720. }
  721. ytwp.pageReady = true;
  722. },
  723. onDispose: function() {
  724. ytwp.log('onDispose');
  725. ytwp.initialized = false;
  726. ytwp.pageReady = false;
  727. ytwp.isWatchPage = false;
  728. },
  729. addBodyClass: function() {
  730. // Insert CSS Into the body so people can style around the effects of this script.
  731. document.body.classList.add(scriptBodyClassId);
  732. ytwp.log('Applied ' + scriptBodySelector);
  733. },
  734. removeBodyClass: function() {
  735. document.body.classList.remove(scriptBodyClassId);
  736. ytwp.log('Removed ' + scriptBodySelector);
  737. },
  738. };
  739.  
  740. ytwp.html5PlayerFix = function() {
  741. ytwp.log('html5PlayerFix');
  742. return;
  743.  
  744. try {
  745. if (!uw.ytcenter // Youtube Center
  746. && !uw.html5Patched // Youtube+
  747. && (!ytwp.html5.app)
  748. && (uw.ytplayer && uw.ytplayer.config)
  749. && (uw.yt && uw.yt.player && uw.yt.player.Application && uw.yt.player.Application.create)
  750. ) {
  751. ytwp.html5.app = ytwp.html5.getPlayerInstance();
  752. }
  753.  
  754. ytwp.html5.update();
  755. ytwp.html5.autohideControls();
  756. } catch (e) {
  757. ytwp.error(e);
  758. }
  759. }
  760.  
  761. ytwp.fixMasthead = function() {
  762. ytwp.log('fixMasthead');
  763. var el = document.querySelector('#masthead-positioner-height-offset');
  764. if (el) {
  765. ytwp.fixMastheadElement(el);
  766. }
  767. }
  768. ytwp.fixMastheadElement = function(el) {
  769. ytwp.log('fixMastheadElement', el);
  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. JSStyleSheet.injectIntoHeader(scriptStyleId + '-focusfix', 'input#search[autofocus] { display: none; }');
  779. ytwp.removeSearchAutofocus = function() {
  780. var e = document.querySelector('input#search');
  781. // ytwp.log('removeSearchAutofocus', e)
  782. if (e) {
  783. e.removeAttribute('autofocus')
  784. }
  785. }
  786.  
  787. ytwp.registerMastheadFix = function() {
  788. ytwp.log('registerMastheadFix');
  789. // Fix the offset when closing the Share widget (element.style.height = ~275px).
  790.  
  791. observe('#masthead-positioner-height-offset', {
  792. attributes: true,
  793. }, function(mutation) {
  794. console.log(mutation.type, mutation)
  795. if (mutation.attributeName === 'style') {
  796. var el = mutation.target;
  797. if (el.style.height) { // != ""
  798. setTimeout(function(){
  799. el.style.height = ""
  800. document.querySelector('#appbar-guide-menu').style.marginTop = "";
  801. }, 0);
  802. }
  803.  
  804. }
  805. });
  806. }
  807.  
  808. //--- Material UI
  809. ytwp.materialPageTransition = function() {
  810. ytwp.log('materialPageTransition')
  811. ytwp.init();
  812.  
  813. if (ytwp.isWatchUrl()) {
  814. ytwp.removeSearchAutofocus();
  815. if (enableOnLoad) {
  816. ytwp.event.addBodyClass();
  817. }
  818. // if (!ytwp.html5.app) {
  819. if (!ytwp.initialized) {
  820. ytwp.log('materialPageTransition !ytwp.html5.app', ytwp.html5.app)
  821. setTimeout(ytwp.materialPageTransition, 100);
  822. }
  823. // Focus player
  824. // var moviePlayer = document.querySelector('#movie_player')
  825. // if (moviePlayer) {
  826. // moviePlayer.click()
  827. // }
  828. } else {
  829. ytwp.event.onDispose();
  830. document.body.classList.remove(scriptBodyClassId);
  831. }
  832. ytwp.onScroll();
  833. ytwp.fixMasthead();
  834. ytwp.attemptToUpdatePlayer();
  835. };
  836.  
  837. //--- Listeners
  838. ytwp.registerListeners = function() {
  839. ytwp.registerMaterialListeners();
  840. ytwp.registerMastheadFix();
  841. };
  842.  
  843. ytwp.registerMaterialListeners = function() {
  844. // For Material UI
  845. // HistoryEvent.listeners.push(ytwp.materialPageTransition);
  846. // HistoryEvent.startTimer();
  847. // HistoryEvent.inject();
  848. // HistoryEvent.listeners.push(console.log.bind(console));
  849. document.addEventListener('yt-page-data-fetched', ytwp.materialPageTransition)
  850. document.addEventListener('yt-navigate-finish', ytwp.materialPageTransition)
  851.  
  852. // Debugging
  853. // document.addEventListener('yt-navigate-start', function(e){ ytwp.log('document.yt-navigate-start', e)})
  854. document.addEventListener('yt-page-data-fetched', function(e){ ytwp.log('document.yt-page-data-fetched', e)})
  855. document.addEventListener('yt-navigate-finish', function(e){ ytwp.log('document.yt-navigate-finish', e)})
  856. // document.addEventListener('yt-navigate-error', function(e){ ytwp.log('document.yt-navigate-error', e)})
  857. // document.addEventListener('yt-navigate-cache', function(e){ ytwp.log('document.yt-navigate-cache', e)})
  858. // document.addEventListener('yt-navigate-redirect', function(e){ ytwp.log('document.yt-navigate-redirect', e)})
  859. // document.addEventListener('yt-navigate-action', function(e){ ytwp.log('document.yt-navigate-action', e)})
  860. // document.addEventListener('yt-navigate-home-action', function(e){ ytwp.log('document.yt-navigate-home-action', e)})
  861. };
  862.  
  863. ytwp.main = function() {
  864. ytwp.registerListeners();
  865. ytwp.init();
  866. ytwp.fixMasthead();
  867. };
  868.  
  869. ytwp.main();
  870.  
  871. // ytwp.updatePlayerTimerId = 0;
  872. ytwp.updatePlayerAttempts = -1;
  873. ytwp.updatePlayerMaxAttempts = 150; // 60fps = 2.5sec
  874. ytwp.attemptToUpdatePlayer = function() {
  875. // console.log('ytwp.attemptToUpdatePlayer')
  876. if (0 <= ytwp.updatePlayerAttempts && ytwp.updatePlayerAttempts < ytwp.updatePlayerMaxAttempts) {
  877. ytwp.updatePlayerAttempts = 0;
  878. } else {
  879. ytwp.updatePlayerAttempts = 0;
  880. ytwp.attemptToUpdatePlayerTick();
  881. }
  882. // setTimeout(ytwp.updatePlayer, 10000); /// Just in case it's not caught
  883. }
  884. ytwp.attemptToUpdatePlayerTick = function() {
  885. // console.log('ytwp.attemptToUpdatePlayerTick', ytwp.updatePlayerAttempts)
  886. if (ytwp.updatePlayerAttempts < ytwp.updatePlayerMaxAttempts) {
  887. ytwp.updatePlayerAttempts += 1;
  888. ytwp.updatePlayer();
  889. // ytwp.updatePlayerTimerId = setTimeout(ytwp.attemptToUpdatePlayerTick, 200);
  890. requestAnimationFrame(ytwp.attemptToUpdatePlayerTick);
  891. }
  892. }
  893.  
  894. ytwp.updatePlayer = function() {
  895. ytwp.removeSearchAutofocus();
  896. ytwp.enterTheaterMode();
  897. ytwp.detectPlayerUnavailable();
  898. }
  899.  
  900. ytwp.toggleExtension = function() {
  901. document.body.classList.toggle('ytwp-window-player')
  902. ytwp.setTheaterMode(document.body.classList.contains('ytwp-window-player'))
  903. }
  904.  
  905.  
  906. //--- Main
  907. ytwp.materialPageTransition()
  908. setInterval(ytwp.updatePlayer, 2500);
  909.  
  910.  
  911. //--- Keyboard Shortcut
  912. function childOf(child, ancestor) {
  913. var parent = child.parentNode
  914. while (parent) {
  915. if (parent == ancestor) {
  916. return true
  917. }
  918. parent = parent.parentNode
  919. }
  920. return false
  921. }
  922. function cancelIfToggleKey(validKeyCallback, e) {
  923. var isKey = e.key === scriptToggleKey
  924. var validTarget = (
  925. e.target === document.body
  926. || e.target.id === 'player-api'
  927. || e.target.id === 'movie_player'
  928. || childOf(e.target, document.querySelector('#movie_player'))
  929. )
  930. if (validTarget && isKey) {
  931. e.preventDefault()
  932. e.stopPropagation()
  933. console.log('cancelIfToggleKey.validKeyCallback', validKeyCallback, 'e', e)
  934. if (validKeyCallback) {
  935. validKeyCallback()
  936. }
  937. }
  938. }
  939. window.addEventListener('keydown', cancelIfToggleKey.bind(null, ytwp.toggleExtension), true)
  940. window.addEventListener('keyup', cancelIfToggleKey.bind(null, null), true)
  941. // Note: keypress is deprecated
  942. // https://developer.mozilla.org/en-US/docs/Web/API/Element/keypress_event
  943. window.addEventListener('keypress', cancelIfToggleKey.bind(null, null), true)
  944.  
  945.  
  946. //--- Browser Extension
  947. if (typeof browser !== "undefined") {
  948. browser.runtime.onMessage.addListener(request => {
  949. if (request.id == "toggle") {
  950. ytwp.toggleExtension()
  951.  
  952. return Promise.resolve({
  953. enabled: document.body.classList.contains('ytwp-window-player'),
  954. })
  955. } else {
  956. return Promise.reject(new Error('Unreconized message.id'))
  957. }
  958. });
  959. }
  960.  
  961. })(window);